1

I want to store a JSON response in array list so that it will be easy to fetch data and assign it to other variables. This is my JSON response:

{  
    "statusCode":"1001",
    "message":"Success",
    "response":{  
        "holidays":[  
         {  
            "holidayId":78,
            "year":2015,
            "date":"2015-01-01",
            "day":"Thrusday",
            "occasion":"New Year Day",
          },
         {  
            "holidayId":79,
            "year":2015,
            "date":"2015-01-15",
            "day":"Thrusday",
            "occasion":"Pongal/Sankranthi",
            },
         {  
            "holidayId":80,
            "year":2015,
            "date":"2015-01-26",
            "day":"Monday",
            "occasion":"Republic Day",
            }
      ],
    "year":0
   }
}

This is the way I am fetching data from the response:

JSONObject jobj = new JSONObject(result);
String statusCode = jobj.getString("statusCode");

if (statusCode.equalsIgnoreCase("1001"))
{
    System.out.println("SUCCESS!");
    String response = jobj.getString("response");

    JSONObject obj = new JSONObject(response);
    String holidays = obj.getString("holidays");

    ArrayList<HolidayResponse> holidayResponse = holidays; //This stmt. shows me error

}

How do I solve this issue? Please help me.

Veronika Gilbert
  • 471
  • 2
  • 8
  • 16
  • 1
    What makes you think an `ArrayList` will be any easier? Just use Jackson, it has excellent methods to navigate any JSON value – fge Feb 18 '15 at 07:47
  • I have never used Jackson before. Isn't there any other easier way? – Veronika Gilbert Feb 18 '15 at 07:50
  • @Jarrod Roberson,the question was not how to convert a JSONArray to Pojo. It was regarding parsing the JSON object.I understand the question is duplicate but please add an appropriate answer.I agree that the question you indicated is a part of the answer.However it is not the complete answer to the question. – Droidekas Feb 18 '15 at 07:57

1 Answers1

4

that is because of a JSON parse exception: the holidays is a JSON array.Hence the correct way would be:

JSONObject obj = new JSONObject(response);
JSONArray holidays = obj.getJSONArray("holidays");

look here to convert that to array list.

Instead of all this hassle,you could use Gson or Jackson

Community
  • 1
  • 1
Droidekas
  • 3,464
  • 2
  • 26
  • 40