HandyJSON的用法 swift
下载地址
https://github.com/alibaba/HandyJSON
文档详尽,请看GitHub里的文档
HandyJSON 没人维护
现在都用系统json解析了 https://blog.csdn.net/VoidLuffy/article/details/140049718
model需要遵循 HandyJSON 协议,class 类需要实现 init方法,Struct 结构体不需要实现 init方法
1.json 串转 model
class BasicTypes: HandyJSON { var int: Int = 2 var doubleOptional: Double? var stringImplicitlyUnwrapped: String! required init() {} } let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}" if let object = BasicTypes.deserialize(from: jsonString) { print(object.int) print(object.doubleOptional!) print(object.stringImplicitlyUnwrapped) }
2.json 串转 model 数组
class Cat: HandyJSON { var name: String? var id: String? required init() {} } let jsonArrayString: String? = "[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]" if let cats = [Cat].deserialize(from: jsonArrayString) { cats.forEach({ (cat) in // ... }) }
3.字典转 model
var dict = [String: Any]() dict["doubleOptional"] = 1.1 dict["stringImplicitlyUnwrapped"] = "hello" dict["int"] = 1 if let object = BasicTypes.deserialize(from: dict) { // ... }
4.model 转字典
model 转 json 串
class BasicTypes: HandyJSON { var int: Int = 2 var doubleOptional: Double? var stringImplicitlyUnwrapped: String! required init() {} } let object = BasicTypes() object.int = 1 object.doubleOptional = 1.1 object.stringImplicitlyUnwrapped = “hello" print(object.toJSON()!) // serialize to dictionary print(object.toJSONString()!) // serialize to JSON string print(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string
在北京的灯中,有一盏是我家的。这个梦何时可以实现?哪怕微微亮。北京就像魔鬼训练营,有能力的留,没能力的走……