将 JSON 映射为数组或对象

Map JSON either as Array or Object

我有 json 有时显示数组有时显示简单对象

"ownersPeriod" : [
        {
          "dateTo" : "2013-06-17",
          "dateFrom" : "2012-09-15"
        },
        {
          "dateTo" : "2016-06-30",
          "dateFrom" : "2013-06-17"
        },
        {
          "dateTo" : "",
          "dateFrom" : "2016-06-30"
        }
      ],

"ownersPeriod" : {
        "dateTo" : "",
        "dateFrom" : "2008-03-29"
      },

如何将简单对象映射或转换为这种类型的数组

我使用对象映射器映射数组

public var ownersPeriodArray: [Model] = []

我在这里使用 ObjectMapper 库将 json 转换为我的模型 让 model = Mapper().map(JSON: json)

如果您想快速查看代码,可以尝试运行这里的代码:http://online.swiftplayground.run/

import Foundation

let jsonObject = """
{
    "ownersPeriod" : [
        {
          "dateTo" : "2013-06-17",
          "dateFrom" : "2012-09-15"
        },
        {
          "dateTo" : "2016-06-30",
          "dateFrom" : "2013-06-17"
        },
        {
          "dateTo" : "",
          "dateFrom" : "2016-06-30"
        }
      ]
}
""".data(using: .utf8)!

let jsonArray = """
{
    "ownersPeriod" : {
        "dateTo" : "",
        "dateFrom" : "2008-03-29"
      }
}
""".data(using: .utf8)!

struct Owner: Codable {
    let ownersPeriod: CombinedType
}

struct OwnerPeriod: Codable {
    var dateTo: String
    var dateFrom: String
}

enum CombinedType: Codable {
    case array([OwnerPeriod])
    case object(OwnerPeriod)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        do {
            self = try .array(container.decode(Array.self))
        } catch DecodingError.typeMismatch {
            do {
                self = try .object(container.decode(OwnerPeriod.self))
            } catch DecodingError.typeMismatch {
                throw DecodingError.typeMismatch(CombinedType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded type not expected"))
            }
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .array(let array):
            try container.encode(array)
        case .object(let object):
            try container.encode(object)
        }
    }
}

let decoder = JSONDecoder()
let object = try decoder.decode(Owner.self, from: jsonObject)
let array = try decoder.decode(Owner.self, from: jsonArray)

print(object)
print(array)

它打印:

Owner(ownersPeriod: SwiftPlayground.CombinedType.array([SwiftPlayground.OwnerPeriod(dateTo: "2013-06-17", dateFrom: "2012-09-15"), SwiftPlayground.OwnerPeriod(dateTo: "2016-06-30", dateFrom: "2013-06-17"), SwiftPlayground.OwnerPeriod(dateTo: "", dateFrom: "2016-06-30")]))

Owner(ownersPeriod: SwiftPlayground.CombinedType.object(SwiftPlayground.OwnerPeriod(dateTo: "", dateFrom: "2008-03-29")))