【发布时间】:2020-09-23 09:18:40
【问题描述】:
我正在尝试解析来自 alamofire 响应的数据。如果我打印所有响应,效果很好,但如果我想打印 JSON 格式的特定参数,例如“firstName”,它会返回 nil。
AF.request("http://localhost:5000/api/users").responseJSON(completionHandler: { (res) in
switch res.result {
case let .success(value):
let xjson : JSON = JSON(res.value)
print(xjson["firstName"].string)
case let .failure(error):
print(error)
}
})
控制台没有错误
代码如下
AF.request("http://localhost:5000/api/users").responseJSON(completionHandler: { (res) in
switch res.result {
case let .success(value):
let xjson : JSON = JSON(res.value)
print(xjson)
print(xjson["firstName"].string)
case let .failure(error):
print(error)
}
})
返回
[
{
"dateOfBirth" : "1998-11-18T00:00:00.000Z",
"_id" : "5f6a29ed16444afd36e9fe15",
"email" : "sdasd@mail.com",
"__v" : 0,
"firstName" : "adam",
"lastName" : "kowalski",
"accountCreateDate" : "2020-09-22T16:44:29.692Z",
"userPassword" : "12345",
"userLogin" : "loginakowalski"
}
]
nil
【问题讨论】:
-
您能否发布完整的 json 字符串,当您打印整个响应时打印?
-
尝试仅使用 JSON 中的值作为参数而不是 res.value
-
添加了来自控制台的响应
-
您的 JSON 是*数组,而不是字典。这就是它失败的原因。
-
您在 json 中有一个对象数组
[],而不是 json 对象直接{}.. 所以您需要的是firstName,来自 json 数组中的first对象。