I have a json that looks like this:
let jsonString = """
{
"data": [
{
"name": "Apple",
"price": 44,
"available": true
},
{
"name": "Pear",
"price": 27,
"available": false
}
],
"some_stuff": [],
"some_other_stuff": []
}"""
My goal is to parse the content of the data array, specifically in a struct that doesn't care about the availibility attribute. I don't care about the some_stuff and some_other_stuff returned is that json.
- First question: Can I ignore these properties event if they are part of the response at the same level as "data" which I'm interested in? If so, how do I represent and empty array of a type I ignore because I only get empty arrays? (For that part, I chose to represent it as an array of arbitrary chosen type Int?)
I created a struct:
struct Fruit: Codable {
let name: String
let price: Int
}
And a kind of super struct above:
struct WholeResponse: Codable {
let data: [Fruit]
let someStuff: [Int?]
let someOtherStuff: [Int?]
enum CodingKeys: String, CodingKey {
case data
case someStuff = "some_stuff"
case someOtherStuff = "some_other_stuff"
}
struct Fruit: Codable {
let name: String
let price: Int
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let data = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
name = try data.decode(String.self, forKey: .name)
price = try data.decode(Int.self, forKey: .price)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var data = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
try data.encode(name, forKey: .name)
try data.encode(price, forKey: .price)
}
}
But I found myself pretty stuck after doing this:
let jsonData = jsonString.data(using: .utf8)!
let jsonDecoder = JSONDecoder()
let fruits = try jsonDecoder.decode(WholeResponse.self, from: jsonData)
I think I am missing something about the representation of my data and perhaps complicating the thing but can you help me get this data array parsed?
someStuffandsomeOtherStuffthen just delete theletlines where you declare properties for them in your struct. Also you can delete yourinitFromanddecodebecause the right thing will happen all by itself.