1

I am trying to call an API which gives me a json response which I am parsing by using JSON Decoder and decodable structs.

For example, JSON data is:

{
 "value":[
  {
   "name":abc
  },
  {
   "name":null
  }
 ]
}

The structs are something like this:

struct output: Decodable {
    let value: [value]

    enum CodingKeys: String, CodingKey {
        case value = "value"
    }
}

struct value: Decodable {
    let name: String

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

I am not sure how to handle this scenario when I get null values because the decoder gives error serializing JSON.

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
Sanyam koul
  • 87
  • 10

1 Answers1

1

Replace

let name: String

with

let name: String?

{
 "value":[
  {
   "name":"abc"
  },
  {
   "name":null
  }
 ]
}

Also no need for the CodingKeys if the keys are the same

struct Output: Decodable { // start structs with capital letter 
    let value: [Value] 
}

struct Value: Decodable {
    let name: String?
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87