我如何用 Alamofire 解码这个 json?
How can I decode this json with Alamofire?
我只想打印键 "User_number"
的值
[
{
"User_fullname": null,
"User_sheba": null,
"User_modifiedAT": "2019-01-31T18:37:02.716Z",
"_id": "5c53404e91fc822c80e75d23",
"User_number": "9385969339",
"User_code": "45VPMND"
}
]
我想这是一些 JSON Data
格式
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
以下代码接受 Data
并将 "User_number" 保存为 Int
if let json = try? JSONSerialization.jsonObject(with: Data!, options: []) as! NSDictionary {
let User_number= json["User_number"] as! Int
}
我只想打印键 "User_number"
[
{
"User_fullname": null,
"User_sheba": null,
"User_modifiedAT": "2019-01-31T18:37:02.716Z",
"_id": "5c53404e91fc822c80e75d23",
"User_number": "9385969339",
"User_code": "45VPMND"
}
]
我想这是一些 JSON Data
格式
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
do {
let users = try JSONDecoder().decode([User].self, from: data)
} catch { print(error) }
所以,现在您已经 Data
解码为自定义模型的数组。所以如果你想,你可以得到某些 User
和它的 number
属性
let user = users[0]
let number = user.number
以下代码接受 Data
并将 "User_number" 保存为 Int
if let json = try? JSONSerialization.jsonObject(with: Data!, options: []) as! NSDictionary {
let User_number= json["User_number"] as! Int
}