Crash: convert dictionary to Json string in Swift 3

I am trying to convert my quick dictionary to a Json string, but am getting a weird crash by saying

The application terminated due to an uncaught exception "NSInvalidArgumentException", reason: "Invalid type in JSON record (_SwiftValue)"

My code is:

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!

Sincerely.

+4
source share
1 answer

AnyObject. , String swift . , , 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)
    }
+17

Source: https://habr.com/ru/post/1658639/