Skip to content

Instantly share code, notes, and snippets.

@frankus
Created March 7, 2023 16:33
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 frankus/9edc21a56836ec4c44300262b8a08582 to your computer and use it in GitHub Desktop.
Save frankus/9edc21a56836ec4c44300262b8a08582 to your computer and use it in GitHub Desktop.
JSONDecoder data decoding strategy for hexadecimal strings
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)
}
}
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