php - Escape Json Object in a Json response in a special condition


I have a JSON response coming from a Website's Wordpress, and i'm taking this feed from a JSON API.

i have a field calledthumbnail_images, this field in some posts shows up as aJSONArray instead ofJSONObject which causes the App to catch an exception caused by malformed JSON.

Link for it:

Searching for the field's name will show the field as Object and in one case where the post has no thumbnail..etc as an emptyJSONArray.

Is it possible to avoid it? from Client as from PHP side it's impossible, as ive already tried to put the value as an Object when the array is null.

PHP code in the JSON's API's filepost.php

$this->thumbnail_images = $attachment->images;
    $this -> thumbnail_images = json_encode(json_decode ("{}"));

From Android Side, i'm creating an Object which has the fields names, and doing the response vie Retrofit2.




Hope you are doing good.

You can use the options for json_encode to force as an Object instead of Array.

Please find the below code which you can try.

$this->thumbnail_images = $attachment->images;
    $this -> thumbnail_images = json_encode(json_decode ("{}"),JSON_FORCE_OBJECT);

Let me know if it works for you.




This answer suggests using an ArrayObject() for an empty JSON Object when encoding JSON in PHP.

In terms of avoiding it from the client side, you could try using a try-catch like so (NOT tested):

    JSONObject thumbnailImages = json.getJSONObject("thumbnail_images");
    //process images here
} catch (JSONException e){
    //thumbnail images is empty, so returning a JSONArray

Hope this helps!

People are also looking for solutions to the problem: php - What would this regex match?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.