如何使用 Swift JSON Decoder 直接解码字典中包含的数组?
假设我们有一个像这样的 json 对象:
{
"count": 2,
"users": [
{
"name": "tom",
"id": 123
},
{
"name": "cat",
"id": 456
}
]
}
User
结构如下:
struct User: Decodable {
let name: String
let id: Int
}
显然,您可以创建另一个名为 Root
的结构来使用 JSONDecoder< 解码 json 对象/code>:
struct Root: Decodable {
let count: Int,
let users: [User]
}
let root = try JSONDecoder().decode(Root.self, from: json)
let users = root.users
但实际上 Root
对我来说没什么用,嵌套的 users
只是我关心的。那么,如何仅将 users
部分解码为 [User]
而不使用不必要的 Root
结构呢?
Suppose we have a json object like this:
{
"count": 2,
"users": [
{
"name": "tom",
"id": 123
},
{
"name": "cat",
"id": 456
}
]
}
and the User
struct would be like:
struct User: Decodable {
let name: String
let id: Int
}
Obviously you can create another struct named Root
to decode the json object using JSONDecoder
:
struct Root: Decodable {
let count: Int,
let users: [User]
}
let root = try JSONDecoder().decode(Root.self, from: json)
let users = root.users
but actually Root
is useless for me, the nested users
is only what I concerned. So how can I decode only the users
part into [User]
without the needless Root
struct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论