2011-06-13 3 views
1

JSONObject와 JSONArray (둘 중 하나를 반환 할 수 있음)를 처리해야하는 코드 조각이 있습니다. 배열 대신 객체를 받으면 예외가 발생합니다. 한 가지 해결책은 첫 번째 문자가 {또는 a [, 그러나 나는 더 나은 것을 기대하고 있는지 확인하는 것입니다.JSON 구문 분석 문제 - 하나의 코드에서 JSONArray와 JSONObject를 모두 처리하는 방법

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; 

답변

3
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

위대한! 이전에 instanceof를 사용하여 문제를 해결했지만 문제가 훨씬 개선되었습니다. – Suchi