【问题标题】:How can I decode this json with Alamofire? [duplicate]如何用 Alamofire 解码这个 json? [复制]
【发布时间】:2019-02-04 15:18:06
【问题描述】:

我只想打印键 "User_number" 的值

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

【问题讨论】:

标签: ios json swift jsondecoder


【解决方案1】:

我想这是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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 哦,在这种情况下你真的不应该推荐JSONSerialization。无论如何,这是 Swift,使用原生类型 Dictionary 而不是 NSDictionary
    猜你喜欢
    • 2020-08-11
    • 2019-05-12
    • 1970-01-01
    • 2016-01-28
    • 2013-06-27
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多