0

I am confused that one time if single image there then I will get JSON response like this from my API,

{
  "banners": 
{
    "imagepath": "myimg.jpg"
  }
}

And if more than one image there then I get result like this,

   {
  "banners": {
    "imagepath": [
      "myimg.jpg",
      "myimg1.jpg"
    ]
  }
}

How do I handle both result at a same time using JSON parsing?

3
  • 2
    I personally think the API is designed badly. Did you create it? If so, whenever your API only can return 1 image, make it return a list of 1 image. This way you only need one parser for your endpoint. Commented Jun 29, 2018 at 11:29
  • no i havent create this api. I also feel the same but my developer says it is not possible from their side. So its useful if we get it from android side. Thanks anyway @ZUNJAE Commented Jun 29, 2018 at 11:33
  • if u use JSONObject, then you get use JSONObject.get("imagepath") and instanceof to check of what type it is. Depending on the type you manually parse this variable. Commented Jun 29, 2018 at 11:39

1 Answer 1

3

If you can't change the API response then you have to parse the JSON manually like below.

    JSONObject jsonObject = new JSONObject(response); 
    JSONObject jsonObject1 = jsonObject.getJSONObject("banners"); 
    //check the banners is the JSONArray or not
     if (jsonObject1.get("imagepath") instanceof JSONArray) {
    //code for JSON Array
    }else{
    //code for simple one
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.