2

I'm using JSon-RPC library.

Servlet:

I want to put List<Student> into JSonArray that is the same as {["name":"AAA","age":"24"]["name":"BBB","age":"12"]}. JsonArray have a contructor that accepts a Collection being the same as parameter. If result is a JsonObject then I'll response to client with method out.print(instanceJsonObject.toString()). Now I don't know how to response JsonArray from Server to Client.

ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("Vu Duc Hoan", "C1010G", "24"));
list.add(new Student("Vu Duc Hoan2", "C1010G2", "242"));

JSONObject js = new JSONObject();
org.json.JSONArray array = new JSONArray(list);

Client:

Can you tell me how to get data in JsonArray? I'm using $.getJson

btnJson.click(function(){
    $.getJSON("../DemoAjax/Controller?action=getJson",function(data){
});

1 Answer 1

2

I think this is the servlet code you are looking for, but I think you would need to first convert the Student object to the JSONObject and then put the JSONObjects in JSONArray, this tutorial might help you:

JSONObject js = new JSONObject();
org.json.JSONArray jsonArray = new JSONArray(list);

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

PrintWriter out = response.getwriter();

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

In the javascript method the data in function(data) would contain this json-array and you can use this answer to get the data in your html page.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.