Skip to content

Instantly share code, notes, and snippets.

@toshi0383
Created January 31, 2024 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toshi0383/2d64e1fa88211f1703f4b83a6d9b8904 to your computer and use it in GitHub Desktop.
Save toshi0383/2d64e1fa88211f1703f4b83a6d9b8904 to your computer and use it in GitHub Desktop.
import Foundation
// First one fails to be decoded.
//
// [1] dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character '0xa' around line 2, column 0." UserInfo={NSJSONSerializationErrorIndex=16, NSDebugDescription=Unescaped control character '0xa' around line 2, column 0.})))
// [2] Success!
//
// SeeAlso: https://github.com/apple/swift-evolution/blob/main/proposals/0200-raw-string-escaping.md
let literalJSONishString = """
{"message": "bbb\nccc" }
"""
let rawJSONString = #"""
{"message": "bbb\nccc" }
"""#
struct Response: Decodable {
let message: String
}
do {
_ = try JSONDecoder().decode(Response.self, from: literalJSONishString.data(using: .utf8)!)
print("[1] Success!")
} catch {
print("[1] \(error)")
}
do {
_ = try JSONDecoder().decode(Response.self, from: rawJSONString.data(using: .utf8)!)
print("[2] Success!")
} catch {
print("[2] \(error)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment