I have a simple struct to model data from a server response:
struct Object: Codable {
var property: String?
}
I am attempting to verify that the object can be decoded:
let data = """
{
"property": "This is the first sentence.\n\nThis is the second sentence.\n\nThis is the third sentence!\n\nThis is the final sentence.\n\n-Someone"
}
""".data(using: .utf8)!
let object = try! JSONDecoder().decode(Object.self, from: data)
However, I continue to encounter the following error in the console:
__lldb_expr_169/Project.playground:15: 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 line 2, column 44." UserInfo={NSDebugDescription=Unescaped control character around line 2, column 44., NSJSONSerializationErrorIndex=46})))
Decoding the data works as expected when I remove all of the escaped newlines (\n) within the value of the property. Decoding fails as long as there is even one newline remaining in the string.
How can I allow the decoding process to succeed while retaining the newlines that are present?