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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28578493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:51:08  来源:igfitidea点击:

How to store JSON response in an array list?

javajson

提问by Veronika Gilbert

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:

我想将 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
   }
}

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.

我该如何解决这个问题?请帮我。

回答by Droidekas

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

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

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

look hereto convert that to array list.

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

Instead of all this hassle,you could use Gsonor Hymanson

你可以使用GsonHymanson 来代替所有这些麻烦