How to find out if returning a JSONObject or JSONArray with JSON-simple (Java)?

I am in the service and sometimes return something like this:

{ "param1": "value1", "param2": "value2" } 

and sometimes getting a refund as follows:

 [{ "param1": "value1", "param2": "value2" },{ "param1": "value1", "param2": "value2" }] 

How to find out what I get? Both of them evaluate the string when I get getClass (), but if I try to do this:

 json = (JSONObject) new JSONParser().parse(result); 

in the second case, I get an exception

 org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject 

How to avoid this? I just would like to know how to check what I will return to. (The first case sometimes has [] in it, so I cannot make an index, and I would like to make a cleaner way than just checking the first character.

Should there be some method that checks this?

+7
source share
2 answers

Simple Java:

 Object obj = new JSONParser().parse(result); if (obj instanceof JSONObject) { JSONObject jo = (JSONObject) obj; } else { JSONArray ja = (JSONArray) obj; } 

You can also check if JNON is started (implied) with [ or { if you want to avoid the overhead of parsing the wrong JSON type. But be careful with leading spaces.

+19
source

Although this is similar to the above, it is not the default constructor of JSONParser. An error occurred: the JSONParser () constructor is not defined

Use this instead

 JsonElement jsonElement = new JsonParser().parse(jsonString); if (jsonElement.isJsonArray()) { //Your Code } else { //Your Code } 
0
source

All Articles