JSON序列化

数据编码为JSON格式

warning:内容来自Perfect官网:https://www.perfect.org/docs/JSON_zh_CN.html
你可以将一下数据类型直接转换为JSON字符串:

  • String
  • Int/UInt
  • Double
  • Bool
  • Array任意类型的数组
  • Dictionary以字符串为关键词的字典
  • Optional 可选类型
  • 从JSONConvertObject对象继承而来的定制类型

1.编码

let scoreArray: [String:Any] = ["第一名": 300, "第二名": 230.45, "第三名": 150]
let encoded = try scoreArray.jsonEncodedString()
// 结果
{"第二名":230.45,"第一名":300,"第三名":150}

2.解码JSON数据

let encoded = "{\"第二名\":230.45,\"第一名\":300,\"第三名\":150}"
let decoded = try encoded.jsonDecode() as? [String:Any]
// 结果
["第二名": 230.44999999999999, "第一名": 300, "第三名": 150]

3.类编码为JSON字符串

  • 类定义
class User: JSONConvertibleObject {
    static let registerName = "user"
    var firstName = ""
    var lastName = ""
    var age = 0
    override func setJSONValues(_ values: [String : Any]) {
        self.firstName = getJSONValue(named: "firstName", from: values, defaultValue: "")
        self.lastName = getJSONValue(named: "lastName", from: values, defaultValue: "")
        self.age = getJSONValue(named: "age", from: values, defaultValue: 0)
    }
    override func getJSONValues() -> [String : Any] {
        return [
            JSONDecoding.objectIdentifierKey:User.registerName,
            "firstName":firstName,
            "lastName":lastName,
            "age":age
        ]
    }
}
  • 注册定义好的类信息
// 运行一次即可
JSONDecoding.registerJSONDecodable(name: User.registerName, creator: { return User() })
  • 对象编码
let user = User()
user.firstName = "Donnie"
user.lastName = "Darko"
user.age = 17
let encoded = try user.jsonEncodedString()
// 结果
{"lastName":"Darko","age":17,"_jsonobjid":"user","firstName":"Donnie"}
  • 对象解码
guard let user2 = try encoded.jsonDecode() as? User else {
    return // 出错
}
// 验证属性值是否一致
XCTAssert(user.firstName == user2.firstName)
XCTAssert(user.lastName == user2.lastName)
XCTAssert(user.age == user2.age)

你可能感兴趣的:(JSON序列化)