I am new to JSON and jQuery and I want to get JSON data using AJAX. I want to show data using a submit button I try like this:
PrintWriter out = response.getWriter();
List<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
JSONObject js = new JSONObject();
JSONArray jsonArray = new JSONArray(country);
// set the response content-type
response.setContentType("application/json");
// writing the json-array to the output stream
out.print(jsonArray);
out.flush();
I get a compile time error: The constructor JSONArray(List<Countries>) is undefined.
below way i try it working but i want to implemt using jason array
PrintWriter out = response.getWriter();
ArrayList<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
String json = new Gson().toJson(country);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.write(json);
working below way
ArrayList<Countries> country=new ArrayList<Countries>();
country=FetchData.getAllCountries();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(country, new TypeToken<List<Countries>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);