Deserialize JSON / NSDictionary to Swift objects

前端 未结 13 1511
情歌与酒
情歌与酒 2020-11-29 18:43

Is there a way to properly deserialize a JSON response to Swift objects resp. using DTOs as containers for fixed JSON APIs?

Something similar to http://james.newtonk

13条回答
  •  無奈伤痛
    2020-11-29 18:57

    HandyJSON is another option to deal with JSON for you. https://github.com/alibaba/handyjson

    It deserials JSON to object directly. No need to specify mapping relationship, no need to inherit from NSObject. Just define your pure-swift class/struct, and deserial JSON to it.

    class Animal: HandyJSON {
        var name: String?
        var id: String?
        var num: Int?
    
        required init() {}
    }
    
    let jsonString = "{\"name\":\"cat\",\"id\":\"12345\",\"num\":180}"
    
    if let animal = JSONDeserializer.deserializeFrom(jsonString) {
        print(animal)
    }
    

提交回复
热议问题