本文介绍了iOS - 在Swift中使用NSJSONSerialization解析JSON字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i am using my REST Webservice to get the JSON Data i want, this works as intended and prints:

 [{
    "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个元素的数组,它们是字典。

So this seems to be an Array with 2 Elements which are Dictionaries.

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

I then tried to parse the JSON with NSJSONSerialization.

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).

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

which seems pretty clear to me, but i just don't know how to solve it.

我的目标是从我自己的班级创建事件对象。

My goal would be to create "Event" Objects from my own class.

推荐答案

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

The result of the deserialization will be an array:

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)")
}

这篇关于iOS - 在Swift中使用NSJSONSerialization解析JSON字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 04:11