0

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);
5
  • 3
    The error means JSONArray does not accept a List / or only a List in it's constructor. Commented May 6, 2014 at 8:41
  • Which JSON library are you using? Commented May 6, 2014 at 8:45
  • arraylist response using jsaon array is possible or any other solution Commented May 6, 2014 at 8:45
  • json-simple-1.1.1.jar lib used Commented May 6, 2014 at 8:45
  • Look what I found! code.google.com/p/json-simple/wiki/EncodingExamples .... its the Wiki for that json library, it contains encoding examples. Check them out. Commented May 6, 2014 at 8:51

2 Answers 2

1

Is that the json-simple library you're using? If it is:

PrintWriter out = response.getWriter();
List<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
JSONObject js = new JSONObject();
js.put("countries", country); // make sure the Country class overrides toString()

// set the response content-type
response.setContentType("application/json");

// writing the json-array to the output stream
out.print(js.toJSONString());
out.flush();

You seem to be trying to insert an anonymous array into your json string. You can't do that, it's not valid JSON. For example, your JSON cannot look like:

{
    ["1st Country", "2nd Country", "3rd Country"]
}

...there needs to be at least one key/value pair in JSON e.g.

{
    "countries": ["1st Country", "2nd Country", "3rd Country"]
}    

...so "countries" is the key and the array is the value. If you use the example code I gave above, then your server should return a JSON string to the browser that looks like the valid JSON example above. So, if your client javascript is calling the server using an AJAX call like this (using jQuery):

$.ajax({
    type:     'GET',
    url:      '/your-server-path',
    dataType: 'json',
    success:  function(response, status, request) {
        // jQuery automatically converts the JSON object to a Javascript object 
        for (int i=0; i<response.countries.length; i++) {
            console.log("Country " + i + " is " + response.countries[i]);
        }
    }, 
    error: function(request, status, error) {
        console.log("Something went wrong...");
    }
});

Also, as I mentioned in the first code snippet, you must override the toString() method of your Country class, so that each Country instance can be converted to a string and added to the JSON array e.g.

@Override
public String toString() {
    // return some combination of variables in your Country class
    // or however you want a Country to be represented
}
Sign up to request clarification or add additional context in comments.

2 Comments

client side which way to set resopnse because above way implmenting got error errror (object object)
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);
0

From the Wiki for json-simple https://code.google.com/p/json-simple/wiki/EncodingExamples#Example_2-4_-_Encode_a_JSON_array_-_Using_List_and_streaming

LinkedList list = new LinkedList();
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
StringWriter out = new StringWriter();
JSONValue.writeJSONString(list, out);
String jsonText = out.toString();
System.out.print(jsonText);

So yours would be

PrintWriter out = response.getWriter();
List<Countries> country = new ArrayList<Countries>();
country = FetchData.getAllCountries();
JSONObject js = new JSONObject();
JSONArray jsonArray = new JSONArray(country);

StringWriter out = new StringWriter();
JSONValue.writeJSONString(country, out);

// set the response content-type
response.setContentType("application/json");

// writing the json-array to the output stream
out.print(out.toString());
out.flush();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.