0

我发现了很多关于实现解码异构对象数组的示例,但它们并不真正适合我的情况。

这是我的 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
    }
}

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

4

1 回答 1

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]
}

marineReports并且specialReports是可选的,因为它们可能不存在。

于 2018-08-01T14:19:19.197 回答