2015-10-19 153 views
2
解析JSON字典與NSJSONSerialization

我用我的REST web服務來獲取JSON數據,我想,這個工程按預期和打印:iOS版 - 斯威夫特

[{ 
    "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). 

這似乎很清楚,我,但我只是不知道如何解決它。

我的目標是從我自己的班級創建「事件」對象。

+0

'json'是字典的陣列。用那個'json [「name」]'你假設它是一本字典,不是。所以'json [0] ['name']'? – Larme

+0

你試過了SwiftyJSON嗎? –

回答

2

反序列化的結果將是一個磁盤陣列:

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

非常感謝! – Bioaim