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

时间:2016-10-24 03:24:26

标签: json swift3

我正在尝试将我的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)
}

请帮助我!

问候。

1 个答案:

答案 0 :(得分:23)

字符串的类型不是 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)
    }