Chris126
Chris126

Reputation: 35

Error with creating an Array of JSON objects in swift

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

Answers (1)

The Mach System
The Mach System

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

Related Questions