-1

Sometimes my JSON response is like this

  {
 "products": [
             {
          "pId": "3564225",
           "name": "Maxi Skirt",
           "slug": "maxi-skirt",
            "sku": "s-navy",
            "priority": 10,
            "images": [

      ]
    },
    {
      "pId": "299328304",
      "name": "Necklace Setjewellery",
      "slug": "american-diamond-necklace-setjewellery",
      "sku": "free-size-purple",
      "priority": 10,
      "images": [

      ]
    }],
    "total": 2
}   

And Sometimes it looks like this

{
  "products": [

  ],
  "total": 0
}

Swift decoder throws following error when parsing empty array response

"*Swift.DecodingError.Context(codingPath: [], debugDescription: 
"The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 
"JSON text did not start with array or object and option to allow fragments not set." 
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}*"

How do I write a swift codable struct to handle multiple response JSON like these above?

PS: I can't change anything from server side.

johndoe
  • 4,387
  • 2
  • 25
  • 40
imgroot
  • 131
  • 3
  • 11

2 Answers2

1

Both JSON objects are valid and can be decoded into

struct Root: Decodable {
    let products : [Product]
    let total: Int
}

struct Product: Decodable {
    let pId, name, slug, sku : String
    let priority : Int
    let images : [Image]
}

struct Image: Decodable {
    let url : URL
}

As images is empty I just assume that there is an URL. Change it to the real property name(s) and type(s)

vadian
  • 274,689
  • 30
  • 353
  • 361
-1

Just refer the following link... https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1

You will get all the stuffs about your issues and more informations in order to decrease further issues and improve your code structure.

  • hmm.. it is just simple tutorial to work with codable , doesnt give any information on handling multiple json reponses. – imgroot Sep 12 '18 at 07:29
  • The linked article suggests to make all properties carelessly optional. That's pretty bad habit and defeats the powerful error descriptions of `Codable`. Rather than *nothing happens* catch all possible errors and inform the user (or the developer). – vadian Sep 12 '18 at 07:33