【问题标题】:JSON Parsing issue in swift 3 from Array to dictionaryswift 3中从数组到字典的JSON解析问题
【发布时间】:2016-06-03 07:40:12
【问题描述】:

我有一个 JSON 格式:

{
  "jsonData": {
    "userDetails": [
      {
        "user_id": "a",
        "first_name": "First1",
        "last_name": "Last1",
        "donation_amount": 841,
        "donation_time": 1452678347523
      },
      {
        "user_id": "b",
        "first_name": "First2",
        "last_name": "Last2",
        "donation_amount": 841,
        "donation_time": 1452678347523
      },
      {
        "user_id": "c",
        "first_name": "First3",
        "last_name": "Last3",
        "donation_amount": 841,
        "donation_time": 1452678347523
      }
    ]
  },
  "total_count": 3
}

我正在使用 swiftlyJSON 快速解析:我的代码如下

    private func processProjectDonorsResponse(response: JSON) {
     //add  to  dictionary
        let jsonObject = response.dictionaryObject!["jsonData"]! as AnyObject
        let details = jsonObject["userDetails"] as! [AnyObject]
        var tempModel = [UserModel]()
        for detail in details {
          let user = UserModel(response: detail as! [String: AnyObject])
          tempModel.append(user)
        }
}

它在 swift 2 中运行良好,但现在我已经升级到 swift 3 我在//let details = jsonObject["userDetails"] as! [AnyObject] 行收到警告 如:从字符串转换?!到不相关的类型“[AnyObject]”总是失败,并崩溃。 如何解决这个问题?

【问题讨论】:

    标签: ios json swift swift3


    【解决方案1】:

    您的代码中的问题在于以下行:

    let jsonObject = response.dictionaryObject!["jsonData"]! as AnyObject
    

    只需使用以下代码更改此代码:

    let jsonObject = response.dictionaryObject!["jsonData"]! as! [String: AnyObject]
    

    希望,这对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多