![](/img/trans.png)
[英]Load json from @propertyWrapper in SwiftUI ContentView
[英]Decode to PropertyWrapper from JSON
我想將 JSON 字符串解碼為People
,如下所示。 age
為數字( Int
)類型,以下代碼出錯:
"Expected to decode Dictionary<String, Any> but found a number instead."
我認為這意味着@Age
被視為Dictionary<String, Any>
。
有什么方法可以將 JSON 值解碼為PropertyWrapper
屬性?
let jsonString =
"""
{
"name": "Tim",
"age": 28
}
"""
@propertyWrapper
struct Age: Codable {
var age: Int = 0
var wrappedValue: Int {
get {
return age
}
set {
age = newValue * 10
}
}
}
struct People: Codable {
var name: String
@Age var age: Int
}
let jsonData = jsonString.data(using: .utf8)!
let user = try! JSONDecoder().decode(People.self, from: jsonData)
print(user.name)
print(user.age)
感謝評論,添加它使其工作。
extension People {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
age = try values.decode(Int.self, forKey: .age)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.