首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从JSON解码为PropertyWrapper

从JSON解码为PropertyWrapper
EN

Stack Overflow用户
提问于 2020-05-13 18:08:04
回答 1查看 180关注 0票数 0

我想将JSON字符串解码为People,如下所示。age是数字(Int)类型,下面的代码出现错误:

代码语言:javascript
运行
复制
"Expected to decode Dictionary<String, Any> but found a number instead."

我认为这意味着@Age被当作Dictionary<String, Any>对待。

有没有办法将JSON值解码为PropertyWrapper属性?

代码语言:javascript
运行
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2020-05-13 18:17:36

多亏了这条评论,添加这个使它工作。

代码语言:javascript
运行
复制
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)
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61771805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档