Home > OS >  Clarifications on JSONDecoder when decoding a single value
Clarifications on JSONDecoder when decoding a single value

Time:01-11

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.

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?

CodePudding user response:

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

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

  • Related