0

I working with API in which an object can an be array or it can be any object and I don't know in which scenario it will be object or array so i can't use different object base on some condition.

Unfortunately I've no access to API code so I can't do any changes there. Any trick that I've to do will be on client side.

So what is the best way to handle that scenario.

Edit : Response Example

.
.
  "ecf":"0",
            "place":{  },
            "mn":"1st Test",
            "teams":[  ],
            "past_ings":[  
               {  
                  "s":{  },
                  "d":{  
                     "a":{  
                        "t":{  
                           "i":"5221",
                           "a":"3",
                           "c":"not out",
                           "dt":null,
                           "fd":"0",
                           "bd":"0",
                           "cb":"no",
                           "b":"1",
                           "r":"0",
                           "sr":"0",
                           "four":"0",
                           "six":"0",
                           "name":"Umesh Yadav"
                        }
                     }
                  }
               }
.
.

The object t can be array or it can be object.

Note : I'm using Gson for parsing and using Retrofit in my network layer.

2 Answers 2

2
Object response = json.get("response")
if (response instanceof JSONArray) {
  // It's an array, cast it as a JSONArray to use it.
} else {
  // It's an object, cast it as a JSONObject to use it.
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not doing manual parsion. I'm using Gson and retrofit in my network layer
In that case, can't you just tell Retrofit to expect an Object and then do the check? I'm not that familiar with Retrofit, I'll read up on it.
0

Just define this is Object when parse json by Gson in Java. After that you have manual if then object is array or object.

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.