How to tell if return is JSONObject or JSONArray with JSON-simple (Java)?

北城以北 提交于 2020-01-01 09:09:41

问题


I am hitting a service and sometimes getting back something like this:

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

and sometimes getting return like this:

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

How do I tell which I'm getting? Both of them evaluate to a String when I do getClass() but if I try to do this:

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

on the second case I get an exception

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

How to avoid this? I would just like to know how to check which I'm getting back. (The first case will sometimes have [] in it so I can't do index of and I'd like a cleaner way than just checking the first character.

There has got to be some sort of method that checks this?


回答1:


Simple Java:

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

You could also test if the (purported) JSON starts with a [ or a { if you wanted to avoid the overhead of parsing the wrong kind of JSON. But be careful with leading whitespace.




回答2:


Though it's similar to above one, but their is not default constructor of JSONParser. Error coming was: The constructor JSONParser() is undefined

Use this instead

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


来源:https://stackoverflow.com/questions/16410421/how-to-tell-if-return-is-jsonobject-or-jsonarray-with-json-simple-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!