Failed to parse json data?

use JSONDecoder().decode

to parse data

{"aaa": "value", "bbb": 1}

it generated error:

Unexpected error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 1." UserInfo={NSDebugDescription=No string key for value in object around character 1.}))).

why?

You’ll probably need to post some code and/or do some debugging. Chances are the data isn’t what you think it is, maybe due to some character encoding issue. NSLog the raw data you’re trying to decode and post it here.

You’ll probably need to post some code and/or do some debugging.

Agreed.

@JoePasadena, I tried your JSON here in my office and it works for me:

import Foundation

struct Test : Codable {
    var aaa: String
    var bbb: Int
}
let json = "{\"aaa\": \"value\", \"bbb\": 1}".data(using: .utf8)!
let t = try! JSONDecoder().decode(Test.self, from: json)
print(t) // prints: Test(aaa: "value", bbb: 1)

I recommend that you convert the string to

Data
and then dump the hex of that. You can then look through the data for hidden characters, wonky text encodings, and so on.

You can print a hex dump as follows.

print(json as NSData)

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Failed to parse json data?
 
 
Q