如何将 JSON 字符串转换为字典?

2023-12-07

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

无法转换表达式的类型 (@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 中做了这个函数:

- (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 字符串转换为字典的便捷方法。但如果你有 JSONdata可用,你应该改为处理数据,根本不使用字符串。

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并忘记投射结果。另外,最好检查一下可能存在的错误。最后注意:只有当您的值是字符串时,这才有效。如果它可以是另一种类型,最好像这样声明字典转换:

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

当然,您还需要更改函数的返回类型:

func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 JSON 字符串转换为字典? 的相关文章

  • 如何将我的 json 字符串 avro 二进制编码为字节数组?

    我有一个实际的 JSON 字符串 我需要将其 avro 二进制编码为字节数组 在经历了Apache Avro 规范 http avro apache org docs 1 7 7 spec html 我想出了下面的代码 我不确定这是否是正确
  • 从bigquery中的json字符串中提取键和值,其中json文档中没有指定的键

    我在 bigquery 中有一个表 其中有对象 对于每个对象 我都有一些字符串化的 json 在 json 中 示例行如下所示 ObjectID 1984931229 indexed abstract IndexLength 123 Inv
  • Haskell Data.Decimal 作为 Aeson 类型

    是否可以解析一个数据 十进制 https hackage haskell org package Decimal 0 4 2 docs Data Decimal html使用 Aeson 包从 JSON 获取 假设我有以下 JSON foo
  • Swift 闭包作为 AnyObject

    我尝试使用这个方法 class addMethod 在 Obj c 中使用如下 class addMethod self class selector eventHandler imp implementationWithBlock han
  • Swift 3 中是否提供内置内部函数?

    我可以在 Xcode 自动完成弹出窗口中看到各种内置函数 如 builtin popount builtin clz 等 我不确定这些是从哪里获取的 单击命令不会导致快速定义或任何文档 Swift 3 中是否有 builtin 或等效的内部
  • 无法理解 Java 地图条目集

    我正在看一个 java 刽子手游戏 https github com leleah EvilHangman blob master EvilHangman java https github com leleah EvilHangman b
  • Jackson 将单个项目反序列化到列表中

    我正在尝试使用一项服务 该服务为我提供了一个带有数组字段的实体 id 23233 items name item 1 name item 2 但是 当数组包含单个项目时 将返回该项目本身 而不是包含一个元素的数组 id 43567 item
  • JSON 解析错误:需要“STRING”

    我在用JSONLint http jsonlint com 解析一些 JSON 我不断收到错误 错误 第 1 行解析错误 产品 需要 STRING 却得到 未定义 这是代码 product code Abc123 description S
  • 迭代 NSOrderedSet

    我正在尝试迭代 NSOrderedSet 的实例 像这样的事情 func myFunc var orderedSet NSOrderedSet array 42 43 44 for n in orderedSet NSLog i n 但是
  • 在另一种语言中使用 dateFormatter [重复]

    这个问题在这里已经有答案了 我正在运行一段返回的代码nil在具有不同语言设置的 iPhone 上运行时 代码示例如下所示 let dateFormatter DateFormatter dateFormatter dateFormat MM
  • 从 JSON 响应中删除元素

    我有一个 JSON 字符串 我希望能够从中删除一些数据 以下是 JSON 响应 ResponseType VirtualBill Response BillHeader BillId 7134 DocumentId MN003 052206
  • 在单行上获取 jq 的输出

    我使用以下输出 https stackoverflow com a 40330344 https stackoverflow com a 40330344 issues key status fields status name assig
  • iOS UIButton 带有圆角和背景 bug

    我发现圆形 UIButton 存在一个奇怪的问题 这是我创建此按钮的代码块 let roundedButton UIButton type System roundedButton frame CGRectMake 100 100 100
  • UISearchController 保留问题

    我正在尝试使用 UISearchController 但是我遇到了无法解决的保留问题 MainTableview 有两个部分 第1节 基于某些正则表达式过滤数据 第2节 All Data 我将 UISearchController 添加到我
  • Typescript Map 在使用其函数时抛出错误(mapobject.keys() 不是函数)

    我是 typescript 中的新蜜蜂 在我的 angular4 项目中 我收到一个 json 形式的地图对象 所以我声明了一个如下所示的类
  • 无法将数据加载到 mvc 4 中的 jTable 中

    好的 我第一次尝试 jTable 我可以加载表 但这对我没有什么好处 因为它不会加载我的任何数据 当我调试程序时 我想要的表中的所有行都存储在我的列表中 因此我很困惑为什么当我运行应用程序时会弹出一个对话框 显示 与服务器通信时发生错误 H
  • 更改 R 中 ggplot geom_polygon 的颜色方案

    我正在使用地图库和 ggplot 的 geom polygon 创建地图 我只是想将默认的蓝色 红色 紫色配色方案更改为其他颜色 我对 ggplot 非常陌生 所以如果我没有使用正确的数据类型 请原谅 我使用的数据如下所示 gt head
  • jq中如何分组?

    这是 json 文档 name bucket1 clusterName cluster1 name bucket2 clusterName cluster1 name bucket3 clusterName cluster2 name bu
  • xcode 6.1 (Swift) 中的 SIGABRT 运行时错误

    与最初的代码相比 唯一的更改是在ViewControl swift override func viewDidLoad newMessage hidden true super viewDidLoad Do any additional s
  • 在 UIMenuItem 上设置accessibilityLabel

    我正在尝试设置accessibilityLabel of a UIMenuItem而且似乎没有效果 无论如何 VoiceOver 只是读取项目的标题 let foo UIMenuItem title foo action selector

随机推荐