如何判断返回的是JSON-simple(Java)的JSONObject还是JSONArray?
我正在获得服务,有时会找回这样的东西:
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" }]
我怎么知道我要去哪?当我执行getClass()时,它们两个都评估为字符串,但是如果我尝试这样做:
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
如何避免这种情况?我只想知道如何检查我回来了. (第一种情况有时会包含[]
,因此我无法索引of,并且我希望使用一种更清洁的方法,而不仅仅是检查第一个字符.
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?
简单的Java:
Object obj = new JSONParser().parse(result);
if (obj instanceof JSONObject) {
JSONObject jo = (JSONObject) obj;
} else {
JSONArray ja = (JSONArray) obj;
}
如果您想避免解析错误类型的JSON的开销,还可以测试(声称的)JSON以[
还是{
开头.但是要注意领先的空格.
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.