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

W.v*_*nus 7 json swift3

我正在尝试将我的快速字典转换为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)
}
Run Code Online (Sandbox Code Playgroud)

请帮我!

问候.

Jos*_*ann 24

String不是AnyObject类型.对象是引用类型,但swift中的String具有值语义.一个字符串但是,可以是类型的任何,所以下面的代码工作.我建议你阅读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)
    }
Run Code Online (Sandbox Code Playgroud)