Background: I'm using swift [email protected] and I need to parse json data
AF.request("https://xxx.json").validate().responseDecodable(of: Decodable)
The data looks like:
[
[
"a",
123,
1.0,
],
[
"b",
456,
2.0,
],
]
My code (this is the wrong way):
struct Item: Codable {
var name: String
}
...responseDecodable(of: [Item].self)
Should I use enum instead? I read some similar answers but they all have keys at some point, my data is pure array without keys.
CodePudding user response:
Assuming the types are always the same in the same order this is a simple example how to decode the inner array, the struct member names are arbitrary
struct Item: Decodable {
let name: String
let someInt: Int
let someDouble: Double
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
name = try container.decode(String.self)
someInt = try container.decode(Int.self)
someDouble = try container.decode(Double.self)
}
}
and decode [Item].self