2016-09-29 90 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) 
        } 

       } 

      } 

     }