First off, you should mention which JSON library you are using. It makes life easier for potential answerers. You seem to be using JSON-java (org.json). Is that correct?
Also, it is rather unusual for a program not to know what the structure of the received JSON is. That is one of the reasons JSON library often don't direct support what you want to do. You may want to look into making sure that there is no way to know more clearly what you are getting. Consider this: Once you know if you have an array or object, what is the next step? Do you know the further structure?
As mentioned, JSON-java is a library that doesn't provide a way to do this directly. Basically you can either just try to use JSONObject
and catch the exception and then try JSONArray
(or viceversa). Or you could look at the first (non-whitespace) character of the string to see if it's a {
or a [
.
Alternatively consider using a different JSON library. Jackson, for example, has a different data model structure where JsonObject
and JsonObject
inherit from a common JsonNode
class which you parse into instead and which provides methods to check and access its properties independent from the actual implementation.