Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clarifications on JSONDecoder when decoding a single value

I was trying to perform some tests on JSONDecoder and I’ve encountered a strange behavior. In particular, when I use the following code an error is thrown.

let data = "Sample String".data(using: .utf8)!

do {
    let decoder = JSONDecoder()
    let decoded = try decoder.decode(String.self, from: data)
    print(decoded)
} catch {
    print(error)
}

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))

On the contrary if I put a number as string and Int.self as the decoding type the value is printed correctly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let data = "100".data(using: .utf8)!

do {
    let decoder = JSONDecoder()
    let decoded = try decoder.decode(Int.self, from: data)
    print(decoded)
} catch {
    print(error)
}

100

Any reason why this happens?

>Solution :

because some string is not valid json, but "some string" is.
you need quotes in your string:

let data = "\"Sample String\"".data(using: .utf8)!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading