swift 自带序列化,以及加强操作
2018-11-28 本文已影响8人
lotawei
swift本身支持对象和结构体的json了,不想在集成各种库的话你可以试试CodaBle来json格式化结构体和自定义的对象
将学会如何使用扩展的方式 如何实现一套 嵌套 数组和字典 属性的全属性完全序列化
struct Cat: Codable {
let name: String
let age: Int
}
let kitten = Cat(name: "kitten", age: 2)
let encoder = JSONEncoder()
do {
let data = try encoder.encode(kitten)
_ = try JSONSerialization.jsonObject(with: data, options: [])
// ["name": "kitten", "age": 2]
} catch {
print(error)
}
struct ACat {
let name: String
let age: Int
}
let akitten = ACat(name: "kitten", age: 2)
let mirror = Mirror(reflecting: akitten)
for child in mirror.children {
print("\(child.label!) - \(child.value)")
}
protocol DictionaryValue {
var value: Any { get }
}
extension Int: DictionaryValue { var value: Any { return self } }
extension Float: DictionaryValue { var value: Any { return self } }
extension String: DictionaryValue { var value: Any { return self } }
extension Bool: DictionaryValue { var value: Any { return self } }
//extension Array: DictionaryValue where Element: DictionaryValue {
// var value: Any { return map { $0.value } }
//}
//
//extension Dictionary: DictionaryValue where Value: DictionaryValue {
// var value: Any { return mapValues { $0.value } }
//}
//让本身也支持 array 和 Dictionary类型的也支持
extension Array: DictionaryValue {
var value: Any { return map { ($0 as! DictionaryValue).value } }
}
extension Dictionary: DictionaryValue {
var value: Any { return mapValues { ($0 as! DictionaryValue).value } }
}
extension DictionaryValue {
var value: Any {
let mirror = Mirror(reflecting: self)
var result = [String: Any]()
for child in mirror.children {
// 如果无法获得正确的 key,报错
guard let key = child.label else {
fatalError("Invalid key in child: \(child)")
}
// 如果 value 无法转换为 DictionaryValue,报错
if let value = child.value as? DictionaryValue {
result[key] = value.value
} else {
fatalError("Invalid value in child: \(child)")
}
}
return result
}
}
struct CCat: DictionaryValue {
let name: String
let age: Int
}
let Ckitten = CCat(name: "kitten", age: 2)
print(Ckitten.value)
struct Wizard: DictionaryValue {
let name: String
let cat:CCat
}
let wizard = Wizard(name: "Hermione", cat: Ckitten)
print(wizard.value) //嵌套自定义的对象也能完整序列化
struct Gryffindor: DictionaryValue {
let wizards: [Wizard]
}
let crooks = CCat(name: "Crookshanks", age: 2)
let hermione = Wizard(name: "Hermione", cat: crooks)
let hedwig = CCat(name: "hedwig", age: 3)
let harry = Wizard(name: "Harry", cat: hedwig)
let gryffindor = Gryffindor(wizards: [harry, hermione])
print(gryffindor.value)
输出
name - kitten
age - 2
["age": 2, "name": "kitten"]
["name": "Hermione", "cat": ["age": 2, "name": "kitten"]]
["wizards": [["name": "Harry", "cat": ["age": 3, "name": "hedwig"]], ["name": "Hermione", "cat": ["age": 2, "name": "Crookshanks"]]]]