我正在嘗試UInt32通過init()在 a 中創建自定義來將作為十六進制字串發送的單個 var 解碼為a Codable struct,但希望var自動解碼剩余的s 。
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?
???
}
}
在JSON我得到的是:
{
"bits" : "1a2b3fdd",
"other" : 12.34,
...
}
uj5u.com熱心網友回復:
您可以創建屬性包裝器并為其提供自定義解碼器。然后您可以標記要解碼的屬性:
@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
}
}
游樂場測驗:
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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/405328.html
標籤:
