How can I read in an array of mixed types from a JSON file in Swift?

谁都会走 提交于 2021-01-29 18:23:08

问题


I am currently trying to create a movie search app in Xcode and am having trouble reading in the JSON file from IMDB's API.

API Example: https://sg.media-imdb.com/suggests/h/h.json

I can read in almost the entire file except for the image information ('i') which is stored as an array with a URL (string) and two optional ints for the dimensions.

   struct Response: Codable {
        var v: Int
        var q: String
        var d: [item]
    }
    
    struct item: Codable {
        var l: String
        var id: String
        var s: String
        var i: ??
    }

No matter what type I enter for 'i' the parse fails. I can't create an array with mixed types so I am confused how to continue.

Thanks


回答1:


You need to do some custom decoding here. You can use the nestedUnkeyedContainer method to get the coding container for the array, and decode the array elements one by one.

Here is how you would implement Decodable:

struct Response: Decodable {
     let v: Int
     let q: String
     let d: [Item]
 }
 
struct Item: Decodable {
    let l: String
    let id: String
    let s: String
    let url: String
    let width: Int?
    let height: Int?
    
    enum CodingKeys: CodingKey {
        case l, id, s, i
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        l = try container.decode(String.self, forKey: .l)
        id = try container.decode(String.self, forKey: .id)
        s = try container.decode(String.self, forKey: .s)
        var nestedContainer = try container.nestedUnkeyedContainer(forKey: .i)
        url = try nestedContainer.decode(String.self)
        width = try nestedContainer.decodeIfPresent(Int.self)
        height = try nestedContainer.decodeIfPresent(Int.self)
    }
}

It doesn't seem like you need to conform to Encodable so I didn't include it, but the code should be similar if you ever need to.



来源:https://stackoverflow.com/questions/62907027/how-can-i-read-in-an-array-of-mixed-types-from-a-json-file-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!