0

I need to decode JSON that has multiple keys named the same. The JSON looks like this:

[{"errors":[{"extensions":{"code":"INTERNAL_SERVER_ERROR","reason":"INTERNAL_SERVER_ERROR"},"message":"Unexpected error occurred"}]},{"data":{"createCsrfToken":{"__typename":"CreateCsrfTokenResponse","csrfToken":"frcxsr60fG4nLnW9HuZXDDYUEgiekGryHDa1104dPwnBz8xyhaQtx2WiVcS6pbDoCUOl9S3Q9kxkh0TSJ1LwecquzgIPGGWRu6s0qTVIHDTjdSweCSgBx5gF1kID4LNurUSEKD","appSessionToken":"eJX7jjUuaZccJ4dzLjFXhNYPm60k0SKrOS7jaA1lkWmA10bpfeLjOSCARpSnm8R3xTi4ImC487aQi4kasjEKPJpBYwnzd394Y6NN1U4g5GkQi5TUHo3691fLXLnSEevd"}}},{"errors":[{"extensions":{"code":"INTERNAL_SERVER_ERROR","reason":"INTERNAL_SERVER_ERROR"},"message":"Unexpected error occurred"}]}]

Notice the two keys named errors.

This is the JSONDecoder statement:

let csrfData: [CsrfData] = try JSONDecoder().decode([CsrfData].self, from: uData)

These are the structures I'm using.

struct CsrfExtensions: Decodable {
    let code: String
    let reason: String
}

struct CsrfErrorsArray: Decodable {
    let extensions: CsrfExtensions
//    let message: String
}

struct CsrfToken: Decodable {
    let __typename: String
    let csrfToken: String
    let appSessionToken: String
}

struct CreateCsrfToken: Decodable {
    let createCsrfToken: CsrfToken
}

struct CsrfData: Decodable {
//    let errors: [CsrfErrorsArray]
    let data: CreateCsrfToken
}

I had commented out errors hoping to just skip that completely. So my error may not be related to the multiple errors keys at all.

This is the error I receive:

keyNotFound(CodingKeys(stringValue: "data", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "data", intValue: nil) ("data").", underlyingError: nil))

  1. What is causing the decode to fail?

  2. How do you decode JSON with multiple same name keys in Swift?

Thanks.

tommy
  • 277
  • 2
  • 8

1 Answers1

1

This JSON doesn't have two errors keys. It is an array of objects, and two of those objects each have an errors key, so that's not causing any problem for the decoder. Your problem is that there are two different types of object in this array (data objects and error objects). When you try to decode the first item, there is no data key (which your struct requires), and it fails.

There are many discussions of decoding arrays with different elements ("heterogeneous arrays") on Stack Overflow. One is Decode heterogeneous array JSON using Swift decodable

Rob Napier
  • 286,113
  • 34
  • 456
  • 610