-2

Struggling with figuring out how to treat my decodable array where it has different types and structures. Essentially it is an array of data, which leads to an array of 4 types, and each of these types consists of a further array of search results.

Can you use decodable for arrays that have varying formats? Or is it simply to use object dicts?

I will attach my JSON at the bottom

struct SearchData: Decodable  {
var success: Bool
var server_response_time: Int
var data: [SearchDataType]
}

//This is the array of 3 of the group types: "Movies", "TV-Shows", "Artists"

struct SearchDataType: Decodable   {
let group: String
let data: [SearchDataMovies]
}


// Where group = "Movies"
struct SearchDataMovies: Decodable {
    let title: String
    let year: String
}

// Where group = "TV-Shows"
struct SearchDataTV: Decodable  {
    let title: String
    let year: Int
}
// Where group = "Artists"
struct SearchDataArtists: Decodable  {
    let name: String
}

enter image description here

unicorn_surprise
  • 951
  • 2
  • 21
  • 40

1 Answers1

2

Decodable isn't going to view the strings in your group as different groups. So having group: "group: Movies", "group: Television", and "group: Games" doesn't make sense. All groups are at the same level in your JSON.

This would be your model:

struct SearchData: Decodable  {
var success: Bool
var server_response_time: Int
var data: [SearchDataType]
}

//Group name and array of groups.

struct SearchDataType: Decodable   {
let group: String
let data: [SearchDataForGroup]
}

// Where group = Any Group (“Movies”, “Television”, “Games”, ect.)

struct SearchDataForGroup: Decodable {
let title: String
let year: String
}

If you want to call the name of your groups using decodable:

Declare a variable at the top level:

let allGroupNames = [data] = []

Then in your function for decoding you can pull out all of your group names from the group like this:

let mygroups = try decoder.decode(SearchData.self, from: data)

for groupValue in mygroups.data{

self.all groupNames = groupValue.group
print(groupNames)

}

From there if your intention is to create a tableView with sections you can use:

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return allGroupNames[section].group
}

Not sure if that is your intent, but hopefully this gets you started.

Ronak Patel
  • 609
  • 4
  • 16