Swift JSON string data decoding with escaping character

43 Views Asked by At

I am getting an error when I am going to decode data response which contains escaping character string .

To demonstrate, I created a playground.

import Foundation

struct Example: Decodable {
    let jsonString: String
}

let jsonStr = """
{
    "jsonString": "\\C This is a string with a backslash and no escaping."
}
"""

let jsonData = jsonStr.data(using: .utf8)!

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let example = try decoder.decode(Example.self, from: jsonData)
    
    print(example.jsonString)
} catch {
    print(error)
}

Then I get an error :

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence 'C' around line 2, column 21." UserInfo={NSJSONSerializationErrorIndex=22, NSDebugDescription=Invalid escape sequence 'C' around line 2, column 21.})))

So my question is how to decode such a data in Swift ?

0

There are 0 best solutions below