开发中,不免遇到这种接口,多个接口功能请求一个接口地址,根据command不同去区分。然后拿到接口返回值转成JSON对象。但是呢,接口返回不一定是JSON对象,还有可能是JSON数组。这个时候就需要用到JSONTokener来判断,字符串是JSON对象还是JSON数组了。
注意:JSONTokener和判断条件里的JSONObject、JSONArray都是org.json包下面的,不要引错了
try {
Object json = new JSONTokener(result).nextValue();
if(json instanceof JSONObject){
JSONObject jsonObject = JSON.parseObject(result);
interfaceLog.setResultBean(jsonObject);
}else if (json instanceof JSONArray){
interfaceLog.setResultBean(JSONObject.parseArray(result));
}else{
throw new ServiceException("报文格式错误");
}
} catch (JSONException e) {
throw new ServiceException("报文解析错误");
}