【问题标题】:Parse alamofire response into JSON return nil将 alamofire 响应解析为 JSON 返回 nil
【发布时间】: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 对象。

标签: ios swift alamofire


【解决方案1】:

这个xjsonArrayJSON(看起来是用户)对象。所以你需要访问数组元素如下,

let xjson : JSON = JSON(res.value)
if let firstUser = xjson.array?.first {
    print(firstUser["firstName"] as? String)
}

你也可以把你的JSON回复here,免费获取所需的数据类型和解码代码。

【讨论】:

  • 您的代码返回错误:'(String, JSON)' 类型的值没有下标
  • 只需将xjson.first 替换为xjson.array?.first
  • 我更换了,现在没有错误,但它仍然返回 nil...
  • 我还有一个警告“从 'JSON' 转换为不相关的类型 'String' 总是失败”
  • @Kamran 也将 firstUser["firstName"] as? String 替换为 firstUser["firstName"].stringValue
【解决方案2】:

感谢大家的帮助。下面是返回正确值的代码:

    AF.request("http://localhost:5000/api/users").responseJSON(completionHandler: { (res) in
        
        switch res.result {
        case let .success(value):

            let xjson : JSON = JSON(res.value)
            if let firstUser = xjson.array?.first {
                print(firstUser["firstName"].string!)
            }
        
        case let .failure(error):
            print(error)
        }
    })

【讨论】: