Decoding JSON from api

Hi,

I have a SwiftUI project where I've been getting json from an api and been using it to populate lists etc.

The data was in the form:

[{"PersonID":12345,"Name":"Joe Brown","MemID":2631,"NoOfThings":1}]

and I was able to read it in using the following code:

Code Block
let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let response = try? JSONDecoder().decode([Member].self, from: data) {
                    DispatchQueue.main.async {
                        members = response
                    }
                    return
                }
            }
        }.resume()

However, I've now been given a new api to use and it gives the json in a slightly different (but still valid) format.

{"Table":[{"PersonID":12345,"Name":"Joe Brown","MemID":2631,"NoOfThings":1}]}

This is as there are some calls that will return more than a single table.
It all works fine from android in java, but I can't seen to get it to work properly in Swift 5.

I have a struct that I'm reading the data into

Code Block
let members = [Member]()
struct Member: Hashable, Codable {
    var PersonID: String
    var Name: String
    var MemID: String?
    var NoOfThings: String?
}

And have members as a collection of Member.

I'm thinking there must be a simple way of achieving reading the data from the api in the new form.

Can anyone help with an example please?

Thanks
Answered by OOPer in 664588022
You can decode the result of the new API as [String: [Member]]:
Code Block
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
do {
// Using `try?` is not recommended...
let response = try JSONDecoder().decode([String: [Member]].self, from: data)
DispatchQueue.main.async {
for (table, members) in response {
print(table, members)
//...
}
}
} catch {
print(error)
}
}
}.resume()


Accepted Answer
You can decode the result of the new API as [String: [Member]]:
Code Block
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
do {
// Using `try?` is not recommended...
let response = try JSONDecoder().decode([String: [Member]].self, from: data)
DispatchQueue.main.async {
for (table, members) in response {
print(table, members)
//...
}
}
} catch {
print(error)
}
}
}.resume()


That's sorted it!
Thank you so much, you've been a massive help.
Knew I wasnt a million miles away, but just couldn't quite work out what I was doing wrong.
Decoding JSON from api
 
 
Q