Decoding dynamic JSON structure in swift 4

后端 未结 4 1596
情深已故
情深已故 2021-01-28 16:43

I have the following issue that I\'m not sure how to handle.

My JSON response can look like this:

{ 
  \"data\": {
      \"id\": 7,
      \"         


        
4条回答
  •  花落未央
    2021-01-28 17:12

    You can try

    struct Root: Codable {
        let data: DataUnion
        let error: String?
    }
    
    enum DataUnion: Codable {
        case dataClass(DataClass)
        case datumArray([Datum])
    
        init(from decoder: Decoder) throws {
            let container = try decoder.singleValueContainer()
            if let x = try? container.decode([Datum].self) {
                self = .datumArray(x)
                return
            }
            if let x = try? container.decode(DataClass.self) {
                self = .dataClass(x)
                return
            }
            throw DecodingError.typeMismatch(DataUnion.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for DataUnion"))
        }
    
        func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            switch self {
            case .dataClass(let x):
                try container.encode(x)
            case .datumArray(let x):
                try container.encode(x)
            }
        }
    }
    
    struct Datum: Codable {
        let id: Int
    }
    
    struct DataClass: Codable {
        let id: Int
        let token: String
    }
    

    let res = try? JSONDecoder().decode(Root.self, from:data)
    

提交回复
热议问题