In playgrounds, the following code produces an error:
import Foundation
struct Model: Codable {
let textBody: String
enum CodingKeys: String, CodingKey {
case textBody = "TextBody"
}
}
let json = """
{
"TextBody": "First Line\n\nLastLine"
}
""".data(using: .utf8)!
let model = try! JSONDecoder().decode(Model.self, from: json)
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character around character 27." UserInfo={NSDebugDescription=Unescaped control character around character 27.}))): file MyPlayground.playground, line 19
The JSON above is perfectly valid according to JSONLint. So what gives?
Update:
I need a solution that will handle data returned from an API. Here is something I came up with so far, but it's gross...
if let data = data,
let dataStr = String(data: data, encoding: .utf8),
let cleanData = dataStr.replacingOccurrences(of: "\n", with: "", options: .regularExpression).data(using: .utf8)
{
do {
let response = try JSONDecoder().decode(T.Response.self, from: cleanData)
completion(.success(response))
} catch (let error) {
print(error.localizedDescription)
completion(.failure(ApiError.decoding))
}
}