【问题标题】:JSON Serialization in Swift iOSSwift iOS 中的 JSON 序列化
【发布时间】:2014-06-08 11:23:18
【问题描述】:

如何快速序列化 JSON?我正在尝试使用此方法进行序列化,但它会导致 EXC_BAD_INSTRUCTION。对于下载 JSON 数据,我使用的是 NSURLConnection。

var sJson : NSDictionary = NSJSONSerialization.JSONObjectWithData(nsMutData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

我该如何解决?

问候

【问题讨论】:

  • 你的意思是反序列化数据吗? JSONObjectWithData 会将您的 NSMutableData 对象转换为 NSDictionaryNSArray,因此这是一个反序列化过程。您的代码片段看起来也有效 - 它对我有用。
  • 尝试捕捉错误:var error: NSError?' then pass in &error` 作为JSONObjectWithData的最后一个参数
  • @Bill 做到了,但仍然是同样的问题
  • @rickerbh 我的服务器返回给我这个数据: [{"0":"Saleem Anwar","FullName":"Saleem Anwar","1":"DHQ:Hospital, ","PlaceOfCurrentPosting ":"DHQ: 医院, ","2":"牙医","命名法":"牙医","距离":58.415098441417,"lat_dest":"34.1905283","long_dest":"78.0457054"}, {"0":"Sartaj Ali Shah","FullName":"Sartaj Ali Shah","1":"DHQ:Hospital, Swabi","PlaceOfCurrentPosting":"DHQ:Hospital, Swabi","2":"牙科医生","命名法":"牙科医生","距离":105.26937892754,"lat_dest":"34.1236046","long_dest":"78.4718982"}]

标签: ios json serialization swift


【解决方案1】:

您的根级数据是字典的数组——不是字典;因此将您的行替换为:

var sJson = NSJSONSerialization.JSONObjectWithData(nsMutData, options: .MutableContainers, error: nil) as NSArray

我对其进行了测试,现在它适用于您的数据。

这是我在项目中创建“json.txt”文件后的测试方法:

var filePath  = NSBundle.mainBundle().pathForResource("json", ofType:"txt")
var nsMutData = NSData(contentsOfFile:filePath)
var sJson     = NSJSONSerialization.JSONObjectWithData(nsMutData, options: .MutableContainers, error: nil) as NSArray

【讨论】:

  • 很棒的人。我找不到这么明显的错误。你先生是天才
【解决方案2】:

这是swift 2.0的方式

    let path : String = NSBundle.mainBundle().pathForResource("jsonDict", ofType: "JSON")!;
        let data : NSData = NSData(contentsOfFile: path)!;
        var jsonDictionary : NSDictionary
        do {
             jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! NSDictionary
        } catch {
            print(error)
        }

【讨论】:

    【解决方案3】:

    在 Swift 4+ 中,JSON 序列化最好通过使用 DecodableEncodable 协议来完成。

    还有Ray Wenderlich的详细教程:Encoding and Decoding in Swift

    【讨论】:

    • 你确定吗?
    猜你喜欢
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2015-10-20
    • 2011-12-22
    相关资源
    最近更新 更多