JSONDecoder().decode failing on struct containing array(s)

I am attempting to parse data received from my server. The data is defined by the struct PlayerList (A), and includes 3 arrays, one being the list of Player's ( B ), and the others, String's. When I try to parse the main Struct (PlayerList), I get the error, "typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:..." when calling JSONDecoder().decode() (C).

If I change the data to just be the array of Players, the main struct has no array fields, and JSON.decode() works just fine.
An article I read suggested making that top level struct a 1 element array, which I did, but it didn't help.

(A)
struct PlayerList: Identifiable, Decodable{
var id: Int
var year: String
var years: [String]
var districts: [String]
var players: [Player]
}

(B)
struct Player: Hashable, Identifialbe, Decodable {
var id: Int
var firstName: String
var lastName: String
var district: String
var rating: String
var playerID: Int
var photoID: Int
var fbUserID: String
}

(C)
let decodedPlayerList = try SONDecoder().decode([PlayerList].self, from: data)
This is successful when operating on the Player struct and the data is an array of Player's. Whether it's a single element of an array, or an single struct, the PlayerList (the struct with arrays) yields the typedef error.
Suggestions are most welcome.

Hi. Welcome to the forum.

You probably want to post a sample of the JSON. I'm betting it's not formed right to line up exactly with the types you defined. Also, what's the full error? Does it really end in an ellipsis like that?

Aside, a couple tips...

  1. I think the "Development" category is for topics about developing Swift itself - ie, working on the compiler, libraries, etc. You probably want the "Using Swift" category. I think. Someone will correct me if I'm wrong.
  2. You can enter code with the "Preformatted text" button, or just manually type the triple backticks ``` around a block. That and indentation will make it easier to read your example code or JSON. Inline code uses single backticks. Eg: `foo` → foo
2 Likes
Terms of Service

Privacy Policy

Cookie Policy