【问题标题】:Crash : Convert dictionary to Json string in Swift 3崩溃:在 Swift 3 中将字典转换为 Json 字符串
【发布时间】:2017-03-05 17:59:24
【问题描述】:

我正在尝试将我的 swift 字典转换为 Json 字符串,但说起来却发生了奇怪的崩溃

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“JSON 写入 (_SwiftValue) 中的类型无效”

我的代码:

let jsonObject: [String: AnyObject] = [
            "firstname": "aaa",
            "lastname": "sss",
            "email": "my_email",
            "nickname": "ddd",
            "password": "123",
            "username": "qqq"
            ]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
    // here "decoded" is of type `Any`, decoded from JSON data

    // you can now cast it with the right type
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch {
    print(error.localizedDescription)
}

请帮帮我!

问候。

【问题讨论】:

标签: json swift3


【解决方案1】:

String 不是 AnyObject 类型。对象是引用类型,但 String 在 swift 中具有值语义。但是,String 可以是 Any 类型,因此下面的代码可以工作。我建议你阅读 Swift 中的引用类型和值语义类型;这是一个微妙但重要的区别,它也不同于您对大多数其他语言的期望,其中 String 通常是一种引用类型(包括目标 C)。

    let jsonObject: [String: Any] = [
        "firstname": "aaa",
        "lastname": "sss",
        "email": "my_email",
        "nickname": "ddd",
        "password": "123",
        "username": "qqq"
    ]

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
        // here "jsonData" is the dictionary encoded in JSON data

        let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
        // here "decoded" is of type `Any`, decoded from JSON data

        // you can now cast it with the right type
        if let dictFromJSON = decoded as? [String:String] {
            print(dictFromJSON)
        }
    } catch {
        print(error.localizedDescription)
    }

【讨论】:

  • 感谢您的帮助。
  • try 由 catch 子句处理
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 2015-06-19
相关资源
最近更新 更多