Created
March 7, 2023 16:33
-
-
Save frankus/9edc21a56836ec4c44300262b8a08582 to your computer and use it in GitHub Desktop.
JSONDecoder data decoding strategy for hexadecimal strings
This file contains hidden or 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 MyStruct: Decodable { | |
let data: Data | |
static func decodeHexData(_ decoder: Decoder) throws -> Data { | |
let container = try decoder.singleValueContainer() | |
let stringValue = try container.decode(String.self) | |
guard let data = Data(hexString: stringValue) else { | |
throw MyStructError.invalidHexString(stringValue) | |
} | |
return data | |
} | |
enum MyStructError: Swift.Error { | |
case invalidHexString(String) | |
} | |
} |
This file contains hidden or 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
let jsonDecoder = JSONDecoder() | |
jsonDecoder.dataDecodingStrategy = .custom(MyStruct.decodeHexData(_:)) | |
let json = """ | |
{ | |
"data": "3605ac536759ad548700f5f4" | |
} | |
""" | |
let jsonData = json.data(using: .utf8)! | |
let decodedStruct = try jsonDecoder.decode(MyStruct.self, from: jsonData) | |
print(decodedStruct.data) // "12 bytes" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment