How can I decode this json with Alamofire? [duplicate]

天大地大妈咪最大 提交于 2020-01-17 20:38:54

问题


I want to print just value for key "User_number"

 [
   {
     "User_fullname": null,
     "User_sheba": null,
     "User_modifiedAT": "2019-01-31T18:37:02.716Z",
     "_id": "5c53404e91fc822c80e75d23",
     "User_number": "9385969339",
     "User_code": "45VPMND"
   }
 ]

回答1:


I suppose this is some JSON in Data format

let data = Data("""
[ { "User_fullname": null, "User_sheba": null, "User_modifiedAT": "2019-01-31T18:37:02.716Z", "_id": "5c53404e91fc822c80e75d23", "User_number": "9385969339", "User_code": "45VPMND" } ]
""".utf8)

One way is using SwiftyJSON library, but, this is something what I don't suggest since you can use Codable.


So, first you need custom struct conforming to Decodable (note that these CodingKeys are here to change key of object inside json to name of property of your struct)

struct User: Decodable {

    let fullname, sheba: String? // these properties can be `nil`
    let modifiedAt, id, number, code: String // note that all your properties are actually `String` or `String?`

    enum CodingKeys: String, CodingKey {
        case fullname = "User_fullname"
        case sheba = "User_sheba"
        case modifiedAt = "User_modifiedAT"
        case id = "_id"
        case number = "User_number"
        case code = "User_code"
    }
}

then decode your json using JSONDecoder

do {
    let users = try JSONDecoder().decode([User].self, from: data)
} catch { print(error) }

So, now you have Data decoded as array of your custom model. So if you want to, you can just get certain User and its number property

let user = users[0]
let number = user.number



回答2:


The following code takes takes in Data and saves "User_number" as an Int

if let json = try? JSONSerialization.jsonObject(with: Data!, options: []) as! NSDictionary {
    let User_number= json["User_number"] as! Int
}


来源:https://stackoverflow.com/questions/54519172/how-can-i-decode-this-json-with-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!