2016-09-29 138 views
0

我在我的swift項目中使用本地JSON。我需要提取數組中的數據。我遇到意外的崩潰。iOS swift 3.0本地JSON解析崩潰

我的JSON是:

{ 
cueca =  (
      { 
      agentName = "Sant"; 
      applicationName = "Get CDR Avaya"; 
      body = "Detail of the message."; 
      imageType = 1; 
      messageType = 1; 
      requestTime = "2016-01-01 00:00:04"; 
      sendTime = "2016-01-01 00:00:04"; 
      subject = "Mensagem 05"; 
      }, 
      { 
      agentName = "Sant2"; 
      applicationName = "Script Programming2"; 
      body = "Detail of the message."; 
      imageType = 1; 
      messageType = 1; 
      requestTime = "2016-01-01 00:00:03"; 
      sendTime = "2016-01-01 00:00:03"; 
      subject = "Mensagem 04"; 
      } 
); 
} 

我的代碼是:

let file = Bundle.main.path(forResource: "ABC", ofType: "json")! as NSString 
    let url = URL(fileURLWithPath: file as String) 
    let data = try! Data(contentsOf: url) 
    let json = try! JSONSerialization.jsonObject(with: data) 

我的問題是:

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 6." UserInfo={NSDebugDescription=No string key for value in object around character 6.}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-800.0.46.2/src/swift/stdlib/public/core/ErrorType.swift, line 178

我要進去 「cuaca」 的所有對象,我可以使用該陣列進一步使用。

+0

這意味着不是一個有效的JSON,請檢查一次您的JSON文件 –

回答

0

最後的一個有效json數據的問題,如果你是從服務器或從其他地方獲取JSON數據只是試圖糾正錯誤,同時創造json點頭,而在你的數據,你有數組cueca對象的2個代理記錄。

有效JSON例如:

{ 
    "cueca": [{ 
     "agentName": "Sant", 
     // data so on 
    }, { 
     "agentName": "Sant2", 
     // data so on 
    }] 
} 

這裏字典cueca含有記錄的[]數組

1

崩潰是因爲文件路徑爲零或網址爲零或數據爲零。請添加零支票。試試下面的代碼

if let file:String = Bundle.main.path(forResource: "ABC", ofType: "json") 
     { 
      if let url:URL = URL(fileURLWithPath: file) 
      { 
       if let data:NSData = NSData(contentsOf: url as URL) 
       { 
        do{ 
         _ = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions()) 
        }catch{ 
         print(error) 
        } 

       } 

      } 

     }