[英]Decoding a single var differently in a Decodable struct
I am trying to decode a single var that is sent as a hexadecimal string into a UInt32
by creating a custom init()
in a Codable
struct
, but would like the remaining var
s to be decoded automatically.我正在尝试通过在Codable
struct
中创建自定义init()
来将作为十六进制字符串发送到UInt32
的单个 var 解码,但希望自动解码剩余的var
。
struct MyStruct : Decodable {
var bits : UInt32
var other1 : Double
... // there are 20 more keys
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let string = try? container.decode(String.self, forKey: .bits) {
self.bits = convertToUInt32(string)
}
// Is there a way to decode remaining keys automatically?
???
}
}
The JSON
I get is:我得到的JSON
是:
{
"bits" : "1a2b3fdd",
"other" : 12.34,
...
}
You can create a property wrapper and provide a custom decoder for it.您可以创建属性包装器并为其提供自定义解码器。 Then you can mark the properties that you want to be decoded:然后您可以标记要解码的属性:
@propertyWrapper
struct UInt32Hexa {
var wrappedValue: UInt32
}
extension UInt32Hexa: Decodable {
public init(from decoder: Decoder) throws {
let string = try decoder.singleValueContainer()
.decode(String.self)
guard let value = UInt32(string, radix: 16) else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Corrupted data: \(string)"))
}
self.wrappedValue = value
}
}
Playground testing:游乐场测试:
let json = """
{
"bits" : "1a2b3fdd",
"other" : 12.34
}
"""
struct MyStruct : Decodable {
@UInt32Hexa var bits: UInt32
let other: Double
}
do {
let test = try JSONDecoder().decode(MyStruct.self, from: Data(json.utf8))
print(test.bits) // 439042013
} catch {
print(error)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.