iOS swift 3.0本地JSON解析崩溃

标签 ios objective-c xcode swift3

我在我的 swift 项目中使用本地 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”中的所有对象,我可以使用数组进一步使用。

最佳答案

崩溃是因为文件路径为 nil 或 url 为 nil 或数据为 nil。请添加零检查。试试下面的代码

 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)
                    }

                }

            }

        }

关于iOS swift 3.0本地JSON解析崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766093/

相关文章:

ios - 如何自定义 UIRefreshControl 使下拉高度低于默认值

iphone - 帮助创建与filteredArrayUsingPredicate一起使用的谓词

ios - 在 swift 中使用组件日期时获取递增的日期?

xcode - 禁止实例方法重写链接器警告框架xcode

ios - Storyboard自定义 segue if/else?

objective-c - iOS - FMDB 使用和内存

ios - 空气原生扩展 : iOS packaged dependencies (Firebase)

iphone - UIImagePickerController,检查相机

ios - 在 FBSDKShare 对话框中共享多个图像

ios - 从 NSString 到 NSNumber 转换期间修改数字