【问题标题】:iOS - Parsing JSON Dictionary with NSJSONSerialization in SwiftiOS - 在 Swift 中使用 NSJSONSerialization 解析 JSON 字典
【发布时间】:2015-10-19 22:02:09
【问题描述】:

我正在使用我的 REST Web 服务来获取我想要的 JSON 数据,这可以按预期工作并打印:

 [{
    "name": "Event1",
    "genre": "Party",
    "subtitle": "subtitle1",
    "startDate": "2015-10-10",
    "location": "Anywhere"
  },
  {
    "name": "Event2",
    "genre": "Party",
    "subtitle": "subtitle2",
    "startDate": "2015-10-10",
    "location": "Anywhere"
  }]

所以这似乎是一个包含 2 个元素的数组,它们是字典。

然后我尝试使用 NSJSONSerialization 解析 JSON。

let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]

            if let name = json["name"] as? [String]{
                print(name)
            }
        } catch let error as NSError {
            print("Failed to load: \(error.localizedDescription)")
        }

我确实收到了这个错误:

Could not cast value of type '__NSCFArray' (0x1096c1ae0) to 'NSDictionary' (0x1096c1d60).

这对我来说似乎很清楚,但我只是不知道如何解决它。

我的目标是从我自己的类中创建“事件”对象。

【问题讨论】:

  • json 是一个字典数组。有了json["name"],您就假设它是一本字典,但事实并非如此。那么json[0]['name"]?
  • 你试过 SwiftyJSON 吗?

标签: ios json swift parsing


【解决方案1】:

反序列化的结果将是一个数组:

let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

do {
    let dataArray = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSArray

    for event in dataArray {
        print(event)
    }

} catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
}

【讨论】:

    猜你喜欢
    • 2013-12-22
    • 1970-01-01
    • 2018-09-26
    • 2012-08-28
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多