Display JSON in hierarchical list (SwiftUI)

How do I set “children” from below JSON object? I retrieve data from an API and would like to create a hierarchical list (collapsing cells).

Thanks in advance.

E.g.

File1.swift
struct Structure1: Decodable {
  let items: [Structure2]
}

struct Structure2: Decodable, Identifiable {
  let id = UUID()
  let itemName: String
  var children: [Structure2]? = nil // <-- how to set?
}
File2.swift
class File2: ObservableObject {
  @Published var items: [Structure2] = []

  func callAPI() {
   // ... some code ...

      do {
        let response = try JSONDecoder().decode(Structure1.self, from: json)
        self.items = response.items
      }
  }
}
ContentView.swift
{
  @StateObject private var model = File2()

  var body: some View {
    List(model.items, children: \.children) { item in
      Text(item.itemName)
    }
    .onAppear {
      model.callAPI()
    }
  }
}

JSON

{
	"totalItems": 2,
	"items": [{ // <-- what I would like to display in sub cells 
		"id": 1,
		"itemName": "item1",
		"subItems": [{
			"id": 1,
			"name": "subItem1"
		}, {
			"id": 2,
			"name": "subItem2",
			"otherInfo": "text"
		}],
		"a0": []
	}, {
		"id": 2,
		"itemName": "item2",
		"subItems": [{
			"id": 1,
			"name": "subItem1"

		}, {
			"id": 2,
			"name": "subItem2",
			"otherInfo": "text"
		}],
		"a0": []
	}]
}

Hey @fredrik thanks for including the above code in order to solve this!

Please see the following repo for all of the details: GitHub - agholson/DisplayJsonItemsListiPhoneApp

I changed the ViewModel a bit. It doesn’t have a children attribute. Here’s the updated model for this situation.

I used the following parser to write most of the model code. It’s a great tool that helps with productivity! Very grateful for Stewart Lynch’s iOS Concurrency tutorial, which showed me it