Swift JSON 解码嵌套数组

时间:2021-03-28 01:07:05

标签: json swift

我正在努力解码我尝试使用的这个 JSON。这是 JSON 的示例。

{
    "Thing1":1
    "Thing2":
    {
        "Thing21":2
        "Thing22":
        {
            "Thing221":3
        }        
    }
}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我喜欢使用 QuickType (app.quicktype.io) 为 JSON 生成 Codable 代码。

它输出这个(一旦你修复了初始 JSON 中缺少的逗号):

struct ParentElement: Codable {
    let thing1: Int
    let thing2: Thing2

    enum CodingKeys: String, CodingKey {
        case thing1 = "Thing1"
        case thing2 = "Thing2"
    }
}

// MARK: - Thing2
struct Thing2: Codable {
    let thing21: Int
    let thing22: Thing22

    enum CodingKeys: String, CodingKey {
        case thing21 = "Thing21"
        case thing22 = "Thing22"
    }
}

// MARK: - Thing22
struct Thing22: Codable {
    let thing221: Int

    enum CodingKeys: String, CodingKey {
        case thing221 = "Thing221"
    }
}

然后,你可以这样解析:

func dealWithJSON(jsonData: Data) {
    do {
        let topLevel = try JSONDecoder().decode(ParentElement.self, from: jsonData)
        print(topLevel.thing2.thing21)
    } catch {
        print(error)
    }
}