开发者

JSON parsing problem - how to handle both JSONArray and JSONObject in one piece of code

开发者 https://www.devze.com 2023-03-12 21:56 出处:网络
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

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

;

0

精彩评论

暂无评论...
验证码 换一张
取 消