【问题标题】:parse nested json in arrays like a tree swifty json解析数组中的嵌套 json,如树 swifty json
【发布时间】:2021-12-22 14:14:54
【问题描述】:

我有这个像树一样的 json

{
    "6": {
        "id": "1269",
        "text": "Electronics",
        "parent_id": "0",
        "children": [
            {
                "id": "1414",
                "text": " Computers",
                "parent_id": "1269",
                "children": [
                    {
                        "id": "1415",
                        "text": " Barebone Computers",
                        "parent_id": "1414"
                    },
                    {
                        "id": "1416",
                        "text": " Computer Servers",
                        "parent_id": "1414"
                    },
                    {
                        "id": "1417",
                        "text": " Desktop Computers",
                        "parent_id": "1414"
                    },
                    {
                        "id": "1423",
                        "text": " Laptops",
                        "parent_id": "1414"
                    },
                    {
                        "id": "1425",
                        "text": " Tablet Computers",
                        "parent_id": "1414"
                    },
                    {
                        "id": "1426",
                        "text": " Thin & Zero Clients",
                        "parent_id": "1414",
                        "children": [
                            {
                                "id": "1428",
                                "text": " Zero Client Computers",
                                "parent_id": "1426"
                            }
                        ]
                    }
                ]
            }
        ]
    }
}

每个子字段都有另一个子字段,依此类推。这个 json 是关于产品类别的。您能帮我如何在 SwiftyJson 和Alamofire 中解析它吗?

我有使用 iOS Swift 的经验,但我见过这种 json 格式 第一次

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 这是一个 json,它有许多像“6”这样的对象,但后端生成的对象不止这些。如您所见,这些对象有另一个对象和子字段,看起来像一棵树。我想解析它并将其放入产品类别列表中。请给我一个想法好吗?

标签: ios json swift


【解决方案1】:

你可以有一个 Codable 结构,它有一个自己的数组。我将children 设为可选,这样底部的孩子就不需要引用更多的孩子了。

您也可以编写自己的自定义编码器/解码器实现,这样它就可以将children 变成一个空数组。

您的 Codable 结构将如下所示:

struct Categories: Codable {
    private enum CodingKeys: String, CodingKey {
        case six = "6"
    }

    let six: Product
}

struct Product: Codable {
    let id: String
    let text: String
    let parent_id: String
    let children: [Product]?
}

解码:

let json = """
{
    "6": {
        /* ... */
    }
}
"""

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多