【KakaJSON手册】06_Model转JSON

前面的文章介绍了如何利用KakaJSON进行JSON转Model,从这篇文章开始介绍如何将Model转成JSON

生成JSON和JSONString

struct Car: Convertible {
    var name: String = "Bently"
    var new: Bool = true
    var age: Int = 10
    var area: Float = 0.12345678
    var weight: Double = 0.1234567890123456
    var height: Decimal = 0.123456789012345678901234567890123456789
    var price: NSDecimalNumber = NSDecimalNumber(string: "0.123456789012345678901234567890123456789")
    var minSpeed: Double = 66.66
    var maxSpeed: NSNumber = 77.77
    var capacity: CGFloat = 88.88
    var birthday: Date = Date(timeIntervalSince1970: 1565922866)
    var url: URL? = URL(string: "http://520suanfa.com")
}

let car = Car()
// 将模型实例car转为JSON
let json1 = car.kj.JSONObject()
// 也可以调用全局函数`JSONObject(from:)`
let json2 = JSONObject(from: car)

// 将模型实例car转为JSONString
let jsonString1 = car.kj.JSONString()
// 也可以调用全局函数`JSONString(from:)`
let jsonString2 = JSONString(from: car)
/* {"birthday":1565922866,"new":true,"height":0.123456789012345678901234567890123456789,
 "weight":0.1234567890123456,"minSpeed":66.66,
 "price":0.123456789012345678901234567890123456789,"age":10,
 "name":"Bently","area":0.12345678,"maxSpeed":77.77,
 "capacity":88.88,"url":"http:\/\/520suanfa.com"} */

// 传入`true`代表生成格式化的JSONString
let jsonString3 = car.kj.JSONString(prettyPrinted: true)
let jsonString4 = JSONString(from: car, prettyPrinted: true)
/*
 {
     "height" : 0.123456789012345678901234567890123456789,
     "weight" : 0.1234567890123456,
     "minSpeed" : 66.66,
     "new" : true,
     "maxSpeed" : 77.77,
     "age" : 10,
     "capacity" : 88.88,
     "birthday" : 1565922866,
     "name" : "Bently",
     "price" : 0.123456789012345678901234567890123456789,
     "area" : 0.12345678,
     "url" : "http:\/\/520suanfa.com"
 }
 */

可选类型

// 可选类型的问号?并不会影响JSON或者JSONString的生成

struct Student: Convertible, Equatable {
    var op1: Int? = 10
    var op2: Double?? = 66.66
    var op3: Float??? = 77.77
    var op4: String???? = "Jack"
    var op5: Bool????? = true
    // op6可以是NSArray\Set<CGFloat>\NSSet\NSMutableArray\NSMutableSet类型
    var op6: [CGFloat]?????? = [44.44, 55.55]
}

let jsonString = Student().kj.JSONString()
/*
 {
     "op1" : 10,
     "op4" : "Jack",
     "op2" : 66.66,
     "op5" : true,
     "op6" : [
         44.44,
         55.55
     ],
     "op3" : 77.77
 }
 */

Enum

// 遵守了`ConvertibleEnum`协议、带有RawValue的Enum,能自动将RawValue转为JSON

enum Grade: String, ConvertibleEnum {
    case perfect = "A"
    case great = "B"
    case good = "C"
    case bad = "D"
}

struct Student: Convertible {
    var grade1: Grade = .great
    var grade2: Grade = .bad
}

let jsonString = Student().kj.JSONString()
/* {"grade2":"D","grade1":"B"} */

模型嵌套

struct Book: Convertible {
    var name: String = ""
    var price: Double = 0.0
}

struct Car: Convertible {
    var name: String = ""
    var price: Double = 0.0
}

struct Dog: Convertible {
    var name: String = ""
    var age: Int = 0
}

struct Person: Convertible {
    var name: String = "Jack"
    var car: Car? = Car(name: "Bently", price: 106.666)
    var books: [Book]? = [
        Book(name: "Fast C++", price: 666.6),
        Book(name: "Data Structure And Algorithm", price: 666.6),
    ]
    var dogs: [String: Dog]? = [
        "dog0": Dog(name: "Wang", age: 5),
        "dog1": Dog(name: "ErHa", age: 3),
    ]
}

let jsonString = Person().kj.JSONString()
/*
 {
     "dogs" : {
         "dog0" : {
             "name" : "Wang",
             "age" : 5
         },
         "dog1" : {
             "name" : "ErHa",
             "age" : 3
         }
     },
     "books" : [
         {
             "price" : 666.6,
             "name" : "Fast C++"
         },
         {
             "name" : "Data Structure And Algorithm",
             "price" : 666.6
         }
     ],
     "name" : "Jack",
     "car" : {
         "price" : 106.666,
         "name" : "Bently"
     }
 }
 */

Any

struct Book: Convertible {
    var name: String = ""
    var price: Double = 0.0
}

struct Dog: Convertible {
    var name: String = ""
    var age: Int = 0
}

struct Person: Convertible {
    // `books`也可以是NSArray\NSMutableArray
    var books: [Any]? = [
        Book(name: "Fast C++", price: 666.6),
        Book(name: "Data Structure And Algorithm", price: 666.6),
    ]
    
    // `dogs`也可以是NSDictionary\NSMutableDictionary
    var dogs: [String: Any]? = [
        "dog0": Dog(name: "Wang", age: 5),
        "dog1": Dog(name: "ErHa", age: 3),
    ]
}

let jsonString = Person().kj.JSONString()
/*
 {
     "dogs" : {
         "dog1" : {
             "age" : 3,
             "name" : "ErHa"
         },
         "dog0" : {
             "age" : 5,
             "name" : "Wang"
         }
     },
     "books" : [
         {
             "name" : "Fast C++",
             "price" : 666.6
         },
         {
             "price" : 1666.6,
             "name" : "Data Structure And Algorithm"
         }
     ]
 }
 */

Model数组

struct Car: Convertible {
    var name: String = ""
    var price: Double = 0.0
}

// `models`也可以是NSArray\NSMutableArray
let models = [
    Car(name: "BMW", price: 100.0),
    Car(name: "Audi", price: 70.0),
    Car(name: "Bently", price: 300.0)
]

let jsonString = models.kj.JSONString()
// 也可以使用全局函数`JSONString(from:)`
// let jsonString = JSONString(from: models)
/*
 [
     {
         "name" : "BMW",
         "price" : 100
     },
     {
         "price" : 70,
         "name" : "Audi"
     },
     {
         "price" : 300,
         "name" : "Bently"
     }
 ]
 */

Model Set

struct Car: Convertible, Hashable {
    var name: String = ""
    var price: Double = 0.0
}

let models: Set<Car> = [
    Car(name: "BMW", price: 100.0),
    Car(name: "Audi", price: 70.0),
    Car(name: "Bently", price: 300.0)
]

let jsonString = models.kj.JSONString()
/*
 [
     {
         "price" : 70,
         "name" : "Audi"
     },
     {
         "price" : 300,
         "name" : "Bently"
     },
     {
         "name" : "BMW",
         "price" : 100
     }
 ]
 */

Key处理

struct Dog: Convertible {
    var nickName: String = "Wang"
    var price: Double = 100.6
    
    // 可以通过实现`kj_JSONKey`方法自定义最终生成JSON的key
    func kj_JSONKey(from property: Property) -> JSONPropertyKey {
        switch property.name {
        case "nickName": return "_nick_name_"
        default: return property.name
        }
    }
}

let jsonString = Dog().kj.JSONString()
/* {"price":100.6,"_nick_name_":"Wang"} */
  • kj_JSONKey也支持ConvertibleConfig配置,用法类似于kj_modelKey,参考第三篇文章

值过滤

private let dateFmt: DateFormatter = {
    let fmt = DateFormatter()
    fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
    return fmt
}()

struct Student: Convertible {
    var birthday: Date?

    // 可以通过实现`kj_JSONValue`方法自定义最终生成JSON的value
    func kj_JSONValue(from modelValue: Any?, _ property: Property) -> Any? {
        if property.name != "birthday" { return modelValue }
        // 将`birthday`格式化成字符串后放入JSON
        return birthday.flatMap(dateFmt.string)
    }
}

let time = "2019-08-13 12:52:51"
let date = dateFmt.date(from: time)
let student = Student(birthday: date)
let jsonString = student.kj.JSONString()
/* {"birthday":"2019-08-13 12:52:51"} */
  • kj_JSONValue也支持ConvertibleConfig配置,用法类似于kj_modelKey,参考第三篇文章

监听

struct Car: Convertible {
    var name: String = "Bently"
    var age: Int = 10

    // 当Model即将开始转换为JSON时调用
    func kj_willConvertToJSON() {
        print("Car - kj_willConvertToJSON")
    }

    // 当Model转换JSON完毕时调用
    func kj_didConvertToJSON(json: [String: Any]) {
        print("Car - kj_didConvertToJSON", json)
    }
}
posted @ 2019-08-17 21:37  M了个J  阅读(2306)  评论(0编辑  收藏  举报