Xaxxus
Xaxxus

Reputation: 1839

How to decode JSON starting with "[" using swift Codable Protocol

I have encountered a JSON response from a server and need to handle it.

Basically, the root level of the JSON is an array instead of a dictionary. For example:

[
  {
    "name": "Joe",
    "age": 50
  },
]

I have build a struct conforming to Codable:

struct response: Codable {
    let responseArray: [Person]
}

struct person: Codable {
    let name: String
    let age: Int

    enum CodingKeys: String, CodingKey {
        case name = "name"
        case age = "age"
    }
}

I get the following error when trying to decode it:

▿ DecodingError
  ▿ typeMismatch : 2 elements
    - .0 : Swift.Dictionary<Swift.String, Any>
    ▿ .1 : Context
      - codingPath : 0 elements
      - debugDescription : "Expected to decode Dictionary<String, Any> but found an array instead."
      - underlyingError : nil

Is there a way to handle the array using coding keys if it is not named?

If not, how would one handle this situation?

Upvotes: 1

Views: 100

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100543

The root of the json is an array do deocde should be [Person].self You can try

struct Person: Codable {
    let name: String
    let age: Int  
}
let res = try? JSONDecoder().deocde([Person].self,from:data)
print(res)

Upvotes: 1

Related Questions