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

给你一囗甜甜゛ 提交于 2019-12-04 03:52:07

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.

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