2016-07-14 57 views
-2

我目前正在制作一个移动应用程序,以便与我的web应用程序一起使用django后端。在swift中读取json数据

我做出在迅速向服务器发出请求,然后我回到这个响应

[{"model": "webapp.comment", "pk": 73, "fields": {"commentDescription": "hello there", "owner": 25, "postId": 78}}, 

{"model": "webapp.comment", "pk": 72, "fields": {"commentDescription": "well hi", "owner": 25, "postId": 78}}] 

我如何然后遍历和访问这些值像commentDescriptionownerpk并使用使用它们在我的手机应用像弦乐一样迅速。我试过使用Gloss来读它,但我仍然迷路。

回答

0

你应该试试这个

guard let stringData = JSONSTRING.dataUsingEncoding(NSUTF8StringEncoding, 
      allowLossyConversion: false) else { return } 

     do { 
      if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, 
       options: NSJSONReadingOptions.MutableContainers) 
} catch { 
      logAndError("Got unknown error from server") 
     } 
2

使用 SwiftyJSON

import SwiftyJSON 

let jsonData = JSON(data:data) // data is your NSData JSON response 
for (_,item):(String, JSON) in jsonData { //loop through your json objects 
    print(item["model"].stringValue) 
    print(item["pk"].intValue) 
    print(item["fields"][commentDescription].stringValue) 
    print(item["fields"]["owner"].stringValue) 
    print(item["fields"]["postId"].intValue) 
}