带有Swift的JDS字符串到NSDictionary [英] JSON String to NSDictionary with Swift

查看:65
本文介绍了带有Swift的JDS字符串到NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 NSData Object

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

这行代码是给我这个问题的那个,它会抛出一个 BAD_EXEC_INSTRUCTION

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

我的问题:如何变成 JSON 进入 NSDictionary

MY Question: How can I turn a JSON into an NSDictionary?

推荐答案

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

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.


  1. 你必须确保你的数据对象确实存在

  2. 你必须确保数据对象可以转换为JSON

  3. 你必须确保JSON实际上包含一个词典

你应该使用Swifts条件转换和它的可选绑定功能。

可选绑定如果让JSONData = JSONData 检查JSONData是不是nil 。如果无法接收数据,您使用的强制解包( JSONData!)可能会崩溃。

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

可选绑定如果让json = NSJSONSerialization.JSONObjectWithData 检查数据是否可以转换为JSON对象。条件转换为? NSDictionary 检查JSON对象是否实际上是字典。您目前不使用这些检查,将对象强制转换为NSDictionary。如果对象无效json,或者它不是字典,那么会崩溃。

The optional binding if let json = NSJSONSerialization.JSONObjectWithData checks if the data could be converted to a JSON object. The conditional cast as? NSDictionary checks 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.

我建议这样的事情:

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

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

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

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

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

Make sure to replace fatalError with appropriate error handling in your production code

这篇关于带有Swift的JDS字符串到NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆