Answer the question
In order to leave comments, you need to log in
How to pair complex JSON data?
Good day.
There was a difficulty in training with getting data from json.
I use standard methods for getting data - Codable.
The json itself is
blackstarshop.ru/index.php?route=api/v1/categories
Answer the question
In order to leave comments, you need to log in
You have a JSON curve on the link. In this line
{"id":67,"iconImage":"image\/catalog\/style\/modile\/icons-03.png"
id is of integer type, although it is a string in all other places. struct EntryList: Decodable {
struct DynamicCodingKey: CodingKey {
var stringValue: String
init?(stringValue: String) { self.stringValue = stringValue }
var intValue: Int? { nil }
init?(intValue: Int) { nil }
}
struct Entry: Decodable {
struct Content: Decodable {
struct Subcategory: Decodable {
let id: String
let iconImage: String
let name: String
let sortOrder: String
let type: String
}
let iconImage: String
let iconImageActive: String
let image: String
let name: String
let sortOrder: String
let subcategories: [Subcategory]
}
let name: String
let content: Content
}
let entries: [Entry]
init(from decoder: Decoder) throws {
let entriesContainer = try decoder.container(keyedBy: DynamicCodingKey.self)
entries = try entriesContainer.allKeys.map { key in
print(key)
let content = try entriesContainer.decode(Entry.Content.self, forKey: key)
return Entry(name: key.stringValue, content: content)
}
}
}
var entryList: EntryList?
let task = URLSession
.shared
.dataTask(with: URL(string: "https://blackstarshop.ru/index.php?route=api/v1/categories")!) { (data, _, error) in
guard error == nil else { return }
guard let data = data else { return }
entryList = try! JSONDecoder().decode(EntryList.self, from: data)
}
task.resume()
I think that QuickType will help you navigate deep JSON much faster by parsing what lies there. For example, if you, as a normal person in an array of 255 objects, can skip an empty field for any key, this solution will help. If at least once this situation repeats, it is necessary to put optional instead of the usual value. Enjoy :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question