如何使用Alamofire解码此json?

时间:2019-02-04 15:18:07

标签: ios json swift jsondecoder

我只想打印键"User_number"的值

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

2 个答案:

答案 0 :(得分:3)

我想这是Data格式的JSON

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)

一种方法是使用SwiftyJSON库,但是我不建议这样做,因为您可以使用Codable


因此,首先,您需要符合Decodable的自定义结构(请注意,这些CodingKeys在此处将json内的对象的键更改为您的结构的属性名称)

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"
    }
}

然后使用JSONDecoder

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

因此,现在您已将Data解码为自定义模型的数组。因此,如果需要,您可以仅获取某些User及其number属性

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

答案 1 :(得分:0)

以下代码接受Data,并将“ User_number”另存为Int

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