在swift 4中解码嵌套数组 [英] decoding a nested array in swift 4

查看:41
本文介绍了在swift 4中解码嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下 JSON:

let rawJson =
"""
[
      {
          "id": 1,
          "name":"John Doe"
      },
      {
          "id": 2,
          "name":"Luke Smith"
      },
 ]
"""

User 模型:

struct User: Decodable {
    var id: Int
    var name: String
}

解码非常简单,如下所示:

It's pretty simple to decode, like so:

let data = rawJson.data(using: .utf8)
let decoder = JSONDecoder()
let users = try! decoder.decode([User].self, from: data!)

但是如果 JSON 看起来像这样,其中顶层是一个字典并且需要获取 users 的数组会怎样:

But what if the JSON looks like this, where the top level is a dictionary and need to fetch the array of users:

let json =
"""
{
    "users":
    [
        {
          "id": 1,
          "name":"John Doe"
        },
        {
          "id": 2,
          "name":"Luke Smith"
        },
    ]
}
"""

读取 JSON 的最有效解决方案是什么?我绝对可以像这样创建另一个 struct:

What's the most effective solution to reading the JSON? I could definitely create another struct like this:

struct SomeStruct: Decodable {
    var posts: [Post]
}

并像这样解码:

let users = try! decoder.decode(SomeStruct.self, from: data!)

但是这样做感觉不对,仅仅因为数组嵌套在字典中就创建了一个新的模型对象.

but it doesn't feel right doing it that way, creating a new model object just because the array is nested inside a dictionary.

推荐答案

如果你想利用 JSONDecoder 你必须创建一个嵌套的 struct(ure).

If you want to take advantage of JSONDecoder you have to create a nested struct(ure).

我建议使用名称 Root 作为根对象并将子结构放入 Root

I recommend to use the name Root for the root object and put the child struct into Root

struct Root : Decodable {

    struct User : Decodable {
        let id: Int
        let name: String
    }

    let users : [User]
}

let json = """
{
    "users": [{"id": 1, "name":"John Doe"},
              {"id": 2, "name":"Luke Smith"}]
}
"""

let data = Data(json.utf8)
do {
    let root = try JSONDecoder().decode(Root.self, from: data)
    print(root.users)
} catch {
    print(error)
}

这篇关于在swift 4中解码嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆