0

I am trying to parse JSON which can be

"post" : {
    "name" : “Test”,
    "profiePic" : "thumb_small_1526912131.png",
    "to_uni" : "0",
    "id_user" : "2863",
    "post_type" : "0",
    "likes" : [

    ],
    "tags" : [

    ],
    "to_name" : “Vivek”,
    "comments" : [

    ]
  }

or it can be of following type

"post" : {
    "name" : “Test2”,
    "profiePic" : "thumb_small_1533120835.png",
    "to_uni" : "0",
    "id_user" : "20393",
    "post_type" : "0",
    "likes" : {
      "message" : “Vivek like this."
    },
    "tags" : [

    ],
    "to_name" : “Vv”,
    "comments" : [

    ]
  }

So for parse this using JSONDecoder I have created a struct as follows

Codable Structure dpaste link

And decoding this json as follows

do {
                let responses = try JSONDecoder().decode(Response.self, from: (response?.data!)!)
                print(responses)
            }catch{
                print(error)
            }

But i am getting error just for likes value which is Expected to decode Array but found a dictionary instead. because that value when blank it returns dictionary when contain value it returns array, so how to manage this kind of case in above struct?

Vivek Goswami
  • 432
  • 3
  • 16
  • I'd go by declaring an array of dictionaries for `var likes`. But with a custom init, I'd check if in your JSON it's a single dictionary or an array, and manage the case. – Larme Sep 10 '18 at 14:58
  • Just one value when it contains "message" : “Vivek like this." but as a array @Larme – Vivek Goswami Sep 10 '18 at 15:11
  • 1
    `init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self); if let likesAsArray = try? container.decode([Likes].self, forKey: .likes) { self.likes = likesAsArray } else if let singleLike = try? container.decode(Likes.self, forKey: .likes) { self.likes = [singleLike] } else { self.likes = [] }}`? – Larme Sep 10 '18 at 15:49
  • where to put this? @Larme – Vivek Goswami Sep 11 '18 at 14:05
  • That's a custom init method. Put it in the `Post` structure. – Larme Sep 11 '18 at 14:06
  • this gives me error see this image https://ibb.co/h14Xep @Larme – Vivek Goswami Sep 11 '18 at 14:19
  • You wrote `self =` instead of `self.likes =` the 3 times. – Larme Sep 11 '18 at 14:20
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179824/discussion-between-vivek-goswami-and-larme). – Vivek Goswami Sep 11 '18 at 14:21

0 Answers0