Мне удалось найти решение для вашей проблемы.
Учитывая следующий пример json
let jsonString = """
{
"name": "xxxx",
"title": "xxxxxxx",
"assets": [
{
"items": [
{
"id": "id11",
"desc": "desc11"
}, {
"id": "id12",
}, {
"desc": "desc13"
}]
},{
"items": [
{
"id": "id21",
"desc": "desc21"
}, {
"id": "id22",
}, {
"desc": "desc23"
}]
}]
}
"""
Ваши структуры будут выглядеть следующим образом
struct Media: Codable {
let id,desc: String?
enum CodingKeys: String, CodingKey {
case id,desc
}
}
struct Response: Decodable {
let name,title: String?
let items: [Media]?
enum CodingKeys: String, CodingKey {
case name,title,items
case assets = "assets"
}
// Decoding
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
title = try container.decode(String.self, forKey: .title)
// Here as the assets contains array of object which has a key as items and then again consist of a array of Media we need to decode as below
let assets = try container.decode([[String:[Media]]].self, forKey: .assets)
// At this stage will get assets with a array of array so we first map and retrive the items and then reduce them to one single array
items = assets.compactMap{$0[CodingKeys.items.rawValue]}.reduce([], +)
}
}
В конце пришло время использовать его следующим образом:
let data = jsonString.data(using: .utf8)!
let myResponse = try! JSONDecoder().decode(Response.self, from: data)
Теперь вы можете получить доступ к данным, как показано ниже
myResponse.name
myResponse.title
myResponse.items
Надеюсь, этот базовый код c поможет вам достичь того, что вы хотите делать. И тогда вы можете go впереди и делать больше вложенных парсингов.
Я хотел бы поблагодарить Nic Laughter
за такую подробную статью ; ссылаясь на который мне удалось прийти с вышеуказанным решением.