Last active
June 20, 2020 17:35
-
-
Save swiftyfinch/0b0689b2baf477b607282dd8be1701ea to your computer and use it in GitHub Desktop.
JSON Encoding. https://swiftyfinch.github.io/en/2020-05-19-json-encoding/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct WithoutEscapingSlashesEncoder { | |
private enum EncoderError: InternalError { | |
case dataToUTF8 | |
case utf8ToData | |
} | |
func encode<T: Encodable>(_ object: T) throws -> Data { | |
let jsonEncoder = JSONEncoder() | |
if #available(iOS 13, *) { | |
jsonEncoder.outputFormatting = .withoutEscapingSlashes | |
return try jsonEncoder.encode(object) | |
} else { | |
let data = try jsonEncoder.encode(object) | |
guard let string = String(data: data, encoding: .utf8) | |
else { throw EncoderError.dataToUTF8 } | |
let fixedString = string.replacingOccurrences(of: "\\/", with: "/") | |
guard let fixedData = fixedString.data(using: .utf8) | |
else { throw EncoderError.utf8ToData } | |
return fixedData | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment