如何将 JSON 字符串转换为字典? [英] How to convert a JSON string to a dictionary?

查看:54
本文介绍了如何将 JSON 字符串转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 swift 项目中创建一个函数,将字符串转换为字典 json 格式,但出现一个错误:

I want to make one function in my swift project that converts String to Dictionary json format but I got one error:

无法转换表达式的类型 (@lvalue NSData,options:IntegerLitralConvertible ...

Cannot convert expression's type (@lvalue NSData,options:IntegerLitralConvertible ...

这是我的代码:

func convertStringToDictionary (text:String) -> Dictionary<String,String> {

    var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
    var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
    return json
} 

我在 Objective-C 中创建了这个函数:

I make this function in Objective-C :

- (NSDictionary*)convertStringToDictionary:(NSString*)string {
  NSError* error;
  //giving error as it takes dic, array,etc only. not custom object.
  NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  return json;
}

推荐答案

警告:如果出于某种原因,您必须使用 JSON 字符串,这是一种将 JSON 字符串转换为字典的便捷方法.但是如果你有可用的 JSON 数据,你应该处理数据,而不是使用一个字符串.

Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.

Swift 3

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

let str = "{"name":"James"}"

let dict = convertToDictionary(text: str)

Swift 2

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
        } catch let error as NSError {
            print(error)
        }
    }
    return nil
}

let str = "{"name":"James"}"

let result = convertStringToDictionary(str)

原始 Swift 1 答案:

func convertStringToDictionary(text: String) -> [String:String]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        var error: NSError?
        let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
        if error != nil {
            println(error)
        }
        return json
    }
    return nil
}

let str = "{"name":"James"}"

let result = convertStringToDictionary(str) // ["name": "James"]

if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
    println(name) // "James"
}

在您的版本中,您没有将正确的参数传递给 NSJSONSerialization 并忘记转换结果.此外,最好检查可能的错误.最后一点:这仅在您的值是字符串时才有效.如果可以是另一种类型,最好像这样声明字典转换:

In your version, you didn't pass the proper parameters to NSJSONSerialization and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]

当然你还需要改变函数的返回类型:

and of course you would also need to change the return type of the function:

func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }

这篇关于如何将 JSON 字符串转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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