2015-10-23 65 views
-1

我有下面的函數來獲得外部JSON。得到陣列通過HTTP調用收到的JSON - 斯威夫特的iOS

func httpGet(request: NSURLRequest!, callback: (String, String?) -> Void) { 

    let session = NSURLSession.sharedSession() 
    let task = session.dataTaskWithRequest(request){ 
     (data, response, error) -> Void in 
     if error != nil { 

     } else { 
      let result = NSString(data: data!, encoding: 
       NSASCIIStringEncoding)! 
      callback(result as String, nil) 
     } 
    } 

    task.resume() 
} 

我用下面的代碼調用函數。

httpGet(request){  
    (data, error) -> Void in 
      if error != nil { 
       print(error) 
      } else { 
       print(data) 
      } 
     } 

我得到一個json返回如下。現在我想要一個數組。

[ 
    { 
    "userId": 1, 
    "id": 1, 
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", 
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" 
    }, 
    { 
    "userId": 1, 
    "id": 2, 
    "title": "qui est esse", 
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" 
    }] 

但由於某些原因,我在網上發現的所有功能都會引發一些錯誤。什麼是最好的方式來做到這一點?

+0

陣列的什麼?自定義課程?! –

回答

0

嘗試像

func example(data:NSData){ 
    do{ 
     if let jsonArray = try NSJSONSerialization.JSONObjectWithData(data, options: [NSJSONReadingOptions.MutableContainers]) as? [NSDictionary]{ 
      for json in jsonArray{ 
       // takes all the values 
       let userId = json.objectForKey("userId") as? Int 
       ...... 
      } 
     } 
    }catch{ 
     //handles the error 
    } 
} 
0

1 - 粘貼你的JSON到http://www.json4swift.com

2 - 將生成的類Xcode項目

3 - 在你現有的代碼,請執行以下操作:

httpGet(request){ 
      (data, error) -> Void in 
      if error != nil { 
       print(error) 
      } else { 
       do{ 
        if let jsonArray = try NSJSONSerialization.JSONObjectWithData(data, options: [NSJSONReadingOptions.MutableContainers]) as? [NSDictionary]{ 

         //Here's your array mapped as models 
         let modelsArray = YourModelClassGenerated.modelsFromDictionaryArray(jsonArray) 

        } 
       }catch{ 
        //handles the error 
       } 
      } 
     } 
+1

讓我試試這個,送還給你。 – esafwan