0

I am trying to parse a JSON string which is a collection of multiple 'Countries'. I have created a structure representing the fields in each JSON object and then one for the array. However I keep getting the following error

Error: cannot convert value of type 'CountryList' to specified type 'Country'

Here is my Code (written in Swift Playgrounds)

import Cocoa
let body = """
{"Countries":
[
  {
    "id": 1,
    "name": "USA",
    "capitalCity": 5,
  },
  {
    "id": 2,
    "name": "France",
    "capitalCity": 5,
  }]}
""".data(using: .utf8)

struct Country: Codable {

    let id: Int
    let name: String
    let capitalCity: Int
 
    
}
struct CountryList: Codable {
    
    var Countries: [Country]
    
}



let countryJson: Country = try! JSONDecoder().decode(CountryList.self, from: body!)
print(countryJson)

Thank you for your help.

1
  • 2
    You have declared countryJson to be of type Country, but you are decoding CountryList - You want let countryJson: CountryList = ... Commented Feb 16, 2021 at 23:39

1 Answer 1

1

Replace this line

let countryJson: Country = try! JSONDecoder().decode(CountryList.self, from: body!)

with this:

let countryJson: CountryList = try! JSONDecoder().decode(CountryList.self, from: body!)
Sign up to request clarification or add additional context in comments.

2 Comments

And you also do not need to explicitly declare the type, since it can be inferred.
You're right. It's not needed. But I always prefer leaving the type there in my code to make it clear for my fellow devs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.