Problem parsing a JSON

I have a JSON object as shown:

{ "sales" : [
{ "prod" : "E", "country" : "USA", "price" : 8000 },
{ "prod" : "C", "country" : "USA", "price" : 2000 },
{ "prod" : "E", "country" : "USA", "price" : 6000 },...
] }

I am trying to parse it in my code with the following structure:

struct Sales : Codable {
  let sales: [sale]

struct Sale : Codable {
  let prod: String
  let country: String
  let price: Int

But, I am getting an error which says :
Expected to decode Array but found a dictionary instead."


This is the rest of the code:

var allData : [Sales] = []
self.allData = try! JSONDecoder().decode([Sales].self , from: data)

Any help in pointing out what am I doing wrong will be greatly appreciated!

The issue is likely at the call site. I suspect you're doing something like decoder.decode([sales].self, from: data), and the [sales] here is the issue because you're specifying that you have an Array of sales. I'm just guessing though as you didn't show the rest of the code :slight_smile:

Also note that the standard notation for types in Swift is upper-cased, so to align to it you should name your types Sales and Sale (capitalised)

1 Like

I have added the rest of the code in the Edit section. Does that help?
Also, thank you for letting me know about the standard notation. I have made the changes accordingly.

Yes, it was indeed what I was guessing. Your code is expecting an Array of Sales, but the example JSON you have there has only one.
Note that wrapping a type in square brackets is a short-hand for an Array of the type. i.e. [Sales] = Array<Sales>

Thank you so much for your help!

1 Like
Terms of Service

Privacy Policy

Cookie Policy