如何在数组列表中存储JSON响应?

时间:2015-02-18 07:45:56

标签: java json

我想在数组列表中存储JSON响应,以便轻松获取数据并将其分配给其他变量。 这是我的JSON回复:

{  
    "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
   }
}

这是我从响应中获取数据的方式:

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

}

如何解决此问题?请帮帮我。

1 个答案:

答案 0 :(得分:4)

这是因为JSON解析异常: 假期是一个JSON数组。正确的方法是:

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

查看here将其转换为数组列表。

您可以使用GsonJackson

而不是所有这些麻烦