Reputation: 35
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.
Upvotes: 0
Views: 84
Reputation: 6963
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!)
Upvotes: 1