2015-09-02 33 views
1

我有以下的JSON作爲響應:無法解析JSON數組NSArray的斯威夫特2

[ 
{ 
    "id_post": "1", 
    "id_type": "1", 
    "title": "I hffjj", 
    "body": "nothing at all", 
    "visitors": "0", 
    "extrabutton": "none", 
    "deviceid": "468af7f24ade50c9" 
}, 
{ 
    "id_post": "2", 
    "id_type": "1", 
    "title": "suxk my ", 
    "body": "sssusushshd", 
    "visitors": "0", 
    "extrabutton": "none", 
    "deviceid": "468af7f24ade50c9" 
} 
] 

我試圖解析它作爲一個NSArray如下所示:

let task = session.dataTaskWithRequest(request) { data, response, error in 
      guard data != nil else { 
       print("no data found: \(error)") 
       return 
      } 

      do { 
       if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray { 
        print("Success: \(jsonResult)") 
       } 
      } catch let parseError { 
       print(parseError) 
      } 
     } 

我總是得到錯誤:

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} 

我在做什麼錯?

+0

小點,但如果你把你的警衛改爲'guard let data = data else {....}'你可以在下面的代碼中刪除感嘆號。 – JeremyP

回答

1

你得到的數據顯然不是一個包含JSON的UTF-8字符串。我們可以看到這一點,因爲字符串似乎設置爲

Current character set: utf8 
NULL 

當打印出錯誤信息時。

我會從一個普通的網絡瀏覽器發出URL請求,以確保響應是你所期望的。

+0

迴應是我所期望的。我的問題不是utf8編碼,而是「JSON文本沒有以數組或對象和選項開始,以允許片段未設置。」 utf8在錯誤處理分支 – xanyi

+0

@xanyi昨天你的問題包含第二個錯誤消息,它打印出顯然不是JSON字符串的數據內容。你爲什麼認爲這不相關?它會導致你正在看到的問題, – JeremyP

2

我想你試試這一個,使用允許NSJSONReadingOptions.AllowFragments選項,給你一個正確的JSON

let task = session.dataTaskWithRequest(request) { data, response, error in guard data != nil else { 
      print("no data found: \(error)") 
      return 
      } 

     do { 
      if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments | NSJSONReadingOptions.MutableContainers, error: nil) as? NSArray { 
       print("Success: \(jsonResult)") 
      } 
     } catch let parseError { 
      print(parseError) 
      let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) 
      print("Error could not parse JSON: '\(jsonStr)'") 
     } 
    } 
+0

另一個錯誤:二元運算符不能應用於兩個NSJSONReadingOptions操作數。 – xanyi

+1

嘗試'選項:[。AllowFragments,.MutableContainers]'。語法在Swift 2中發生了變化。 – vacawama

+0

這些選項有效,錯誤是「錯誤域= NSCocoaErrorDomain代碼= 3840」字符0周圍的值無效。「UserInfo = {NSDebugDescription =字符0周圍的值無效}」。 – xanyi

-1

爲SWIFT 3的Xcode 8.1,你可以使用這個:

let jsonResult = try JSONSerialization.jsonObject(with: data!, options: [.allowFragments, .mutableContainers]) 
+2

問題中的JSON不需要任何這些選項,'.mutableContainers'是沒有意義的無論如何Swift。 – vadian