ios 使用 Swift 将 JSON 字符串转换为 NSDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29092101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:14:04  来源:igfitidea点击:

JSON String to NSDictionary with Swift

iosjsonxcodeswift

提问by Arafal

I am trying to create a dictionary from data that is held in a server, I receive the data but I cannot convert the data to an NSDictionary, I believe it is held in an NSDataObject

我正在尝试根据服务器中保存的数据创建字典,我收到数据但无法将数据转换为NSDictionary,我相信它保存在NSData对象中

let JSONDictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(JSONData!, options: nil, error: &error) as NSDictionary

This line of code is the one giving me the problem, it throws a BAD_EXEC_INSTRUCTION.

这行代码给我带来了问题,它抛出一个BAD_EXEC_INSTRUCTION.

MY Question: How can I turn a JSONinto an NSDictionary?

我的问题:我怎样才能把 aJSON变成 an NSDictionary

回答by Matthias Bauch

Your code does not do any error handling. But it can (and if this data comes from a web service, will) fail in multiple ways.

您的代码不进行任何错误处理。但它可能(如果此数据来自 Web 服务,将会)以多种方式失败。

  1. You have to make sure that your data object actually exists
  2. You have to make sure that the data object can be converted to JSON
  3. You have to make sure that the JSON actually contains a Dictionary
  1. 您必须确保您的数据对象确实存在
  2. 您必须确保数据对象可以转换为 JSON
  3. 你必须确保 JSON 实际上包含一个字典

You should use Swifts conditional cast and it's optional binding capabilities.
The optional binding if let JSONData = JSONDatachecks that JSONData is not nil. The force unwrap (JSONData!) you use might crash if no data could be received.

您应该使用 Swifts 条件转换及其可选绑定功能。
可选绑定if let JSONData = JSONData检查 JSONData 是否不为零。JSONData!如果无法接收到数据,您使用的 force unwrap ( ) 可能会崩溃。

The optional binding if let json = NSJSONSerialization.JSONObjectWithDatachecks if the data could be converted to a JSON object. The conditional cast as? NSDictionarychecks if the JSON object is actually a dictionary. You currently don't use these checks, you cast the objects as NSDictionary. Which will crash, if the object is not valid json, or if its not a dictionary.

可选绑定if let json = NSJSONSerialization.JSONObjectWithData检查数据是否可以转换为 JSON 对象。条件转换as? NSDictionary检查 JSON 对象是否实际上是一个字典。您目前不使用这些检查,而是将对象转换为 NSDictionary。如果对象不是有效的 json,或者它不是字典,这将崩溃。

I would recommend something like this:

我会推荐这样的东西:

var error: NSError?
if let JSONData = JSONData { // Check 1
    if let json: AnyObject = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &error) { // Check 2
        if let jsonDictionary = json as? NSDictionary { // Check 3
            println("Dictionary received")
        }
        else {
            if let jsonString = NSString(data: JSONData, encoding: NSUTF8StringEncoding) {
                println("JSON String: \n\n \(jsonString)")
            }
            fatalError("JSON does not contain a dictionary \(json)")
        }
    }
    else {
        fatalError("Can't parse JSON \(error)")
    }
}
else {
    fatalError("JSONData is nil")
}

You could merge check 2 and 3 into one line and check if NSJSONSerialization can create a NSDictionary directly:

您可以将检查 2 和 3 合并为一行并检查 NSJSONSerialization 是否可以直接创建 NSDictionary:

var error: NSError?
if let JSONData = JSONData { // Check 1.
    if let JSONDictionary = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &error) as? NSDictionary { // Check 2. and 3.
        println("Dictionary received")
    }
    else {

        if let jsonString = NSString(data: JSONData, encoding: NSUTF8StringEncoding) {
            println("JSON: \n\n \(jsonString)")
        }
        fatalError("Can't parse JSON \(error)")
    }
}
else {
    fatalError("JSONData is nil")
}

Make sure to replace fatalErrorwith appropriate error handling in your production code

确保fatalError在您的生产代码中使用适当的错误处理进行替换

回答by Ulysses

Update for Swift 2.

Swift 2 的更新。

Now you must use it inside a try catch block.

现在您必须在 try catch 块中使用它。

    do {
        let responseObject = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String:AnyObject]
    } catch let error as NSError {
 print("error: \(error.localizedDescription)")
}

回答by Mohd Prophet

Here jsonResultwill give you the response in NSDictionary:

这里jsonResult会给你回复NSDictionary

let url = NSURL(string: path)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
            println("Task completed")
            if(error != nil) {
                // If there is an error in the web request, print it to the console
                println(error.localizedDescription)
            }
            var err: NSError?
            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
            if(err != nil) {
                // If there is an error parsing JSON, print it to the console
                println("JSON Error \(err!.localizedDescription)")
            }

        })
        task.resume()