Home > Mobile >  SwiftUI: how to add type for JSON with 0 index array key
SwiftUI: how to add type for JSON with 0 index array key

Time:05-17

I am making a API call in swift and the response of the API looks like this:

[
    {
        "response": {
            "data": {
                "first": "Hello",
                "second": "Hola",
                "third": "Namaste"
            }
        }
    }
]

Now to be able to integrate it into my app I need to decode the response from the API call for which the type I am using is as below:

struct APIResponse: Codable {
  let response: Response
}
    
struct Response: Codable {
  let data: Data
}
    
struct Data: Codable {
  let first: String
  let second: String
  let third: String
} 

Now the issue is this type is wrong because the API response is actually a array with only one element (index 0), which means the above type would work if the response from API was

[
  "response": {
    "data": {
      "first": "Hello",
      "second": "Hola",
      "third": "Namaste"
    }
  }
]

how to define index-0 data in my type?

The code I am using to make API call and decode JSON:

var request = URLRequest(url: URL(string: "https://myurl.com")!)
let (data, _) = try await URLSession.shared.data(for: request)
let decodedResponse = try? JSONDecoder().decode(APIResponse.self, from: data)

CodePudding user response:

Your response is an array of elements:

let decodedResponse = try JSONDecoder().decode([APIResponse].self, from: data)

and:

let element = decodedResponse.first

should get you going.

And never use try? it will obfuscate all errors.

  • Related