我有一个服务器默认返回一些JSONArray,但是当发生一些错误时它会返回带有错误代码的JSONObject.我正在尝试解析json并检查错误,我有一段代码检查错误:
public static boolean checkForError(String jsonResponse) {
boolean status = false;
try {
JSONObject json = new JSONObject(jsonResponse);
if (json instanceof JSONObject) {
if(json.has("code")){
int code = json.optInt("code");
if(code==99){
status = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status ;
}
Run Code Online (Sandbox Code Playgroud)
但是当jsonResponse没问题并且它是JSONArray(JSONArray无法转换为JSONOBject)时,我得到JSONException.如何检查jsonResponse是否会为我提供JSONArray或JSONObject?
Raj*_*esh 16
使用JSONTokener
.这JSONTokener.nextValue()
将为您提供一个Object
可以根据实例动态转换为适当类型的内容.
Object json = new JSONTokener(jsonResponse).nextValue();
if(json instanceof JSONObject){
JSONObject jsonObject = (JSONObject)json;
//further actions on jsonObjects
//...
}else if (json instanceof JSONArray){
JSONArray jsonArray = (JSONArray)json;
//further actions on jsonArray
//...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4495 次 |
最近记录: |