崩溃:在 Swift 3 中将字典转换为 Json 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40210266/
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-09-03 18:40:13  来源:igfitidea点击:

Crash : Convert dictionary to Json string in Swift 3

jsonswift3

提问by W.venus

I'm trying to convert my swift dictionary to Json string but getting strange crash by saying

我正在尝试将我的 swift 字典转换为 Json 字符串,但说奇怪的崩溃

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'

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

My code:

我的代码:

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

Please help me!

请帮我!

Regards.

问候。

回答by Josh Homann

Stringis not of type AnyObject. Objects are reference types, but Stringin swift has value semantics. A Stringhowever, can be of type Any, so the code below works. I suggest you read up on reference types and value semantic types in Swift; its a subtle but important distinction and its also different from what you expect from most other languages, where String is often a reference type (including objective C).

String不是AnyObject类型。对象是引用类型,但swift 中的String具有值语义。然而,一个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)
    }