我想将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)
}
}