JSON parsing problem - how to handle both JSONArray and JSONObject in one piece of code
I have a piece of code that needs to handle both JSONObject and JSONArray (开发者_高级运维it might return either). It throws me an exception when I receive an object instead of an array. One solution is to check if the first character is a { or a [, but I am hoping for a better one.
JSONObject responseMsgObject = new JSONObject(dummyJson);
if (responseMsgObject.has("messages")) {
String successString = responseMsgObject.getString("response");
if (successString.equalsIgnoreCase("SUCCESS")) {
JSONArray messageArray = responseMsgObject
.getJSONArray("messages");
return messageArray;
}
} else
return null;
JSONObject responseMsgObject = new JSONObject(dummyJson);
if (responseMsgObject.has("messages")) {
String successString = responseMsgObject.getString("response");
if (successString.equalsIgnoreCase("SUCCESS")) {
JSONArray messageArray = responseMsgObject
.optJSONArray("messages"); //optJSONArray returns null if doesnt exist or is not a JSONArray
if(messageArray!=null){
return messageArray;
}
}
}
else
return null
;
精彩评论