java simple json,如何判断返回的是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" }]

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值