解码异构数组

时间:2018-08-01 14:00:28

标签: json swift parsing codable heterogeneous-array

我发现了很多有关解码异类对象数组的实现的示例,但是它们与我的情况不符。

这是我的JSON:

{
  "response": [
    {
      "label": "Shore",
      "marineReports": [
        {
          "id": 1,
          "label": "Label"
        },
        {
          "id": 2,
          "label": "Label"
        }
      ]
    },
    {
      "label": "Open Sea",
      "marineReports": [
        {
          "id": 0,
          "label": "Label"
        },
        {
          "id": 0,
          "label": "Label"
        }
      ]
    },
    {
      "label": "Offshore",
      "marineReports": [
        {
          "id": 3,
          "label": "Label"
        },
        {
          "id": 3,
          "label": "Label"
        },
        {
          "id": 3,
          "label": "Label"
        }
      ]
    },
    {
      "label": "Special Reports",
      "specialReports": [
        {
          "label": "Atlantic-Channel",
          "reports": [
            {
              "id": 12,
              "label": "Offshore Atlantic"
            },
            {
              "id": 17,
              "label": "Channel"
            }
          ]
        }
      ]
    }
  ]
}

这是我最初实现的:

struct ResponseSea: Codable {
    let result: [SeaArea]
}

struct SeaArea: Codable {
    var label: String
    var reports: [MarineReport]

    struct MarineReport: Codable {
        var id: Int
        var label: String
    }
}

但是后来我发现结果数组中的最后一个对象与其他对象不同。 如何在相同对象类型的数组中为特定对象实现自定义解析逻辑?

1 个答案:

答案 0 :(得分:1)

基于您的JSON,它应该像这样:

struct RootObject: Codable {
    let response: [Response]
}

struct Response: Codable {
    let label: String
    let marineReports: [Report]?
    let specialReports: [SpecialReport]?
}

struct Report: Codable {
    let id: Int
    let label: String
}

struct SpecialReport: Codable {
    let label: String
    let reports: [Report]
}

marineReportsspecialReports是可选的,因为它们可能不存在。