问题
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