var data = [
{lastName: "Dente", name: "Al"},
{lastName: "Noring", name: "Constance"},
{lastName: "Haas", name: "Jack"},
{lastName: "Tress", name: "Matt"},
{lastName: "Turner", name: "Paige"}
];
this is the javascript array i want to create. How to send this data from a servlet and create the array object in javascript.
String dataString=/*prepare data */
response.getWriter().write(dataString);
How to prepare this dataString in servlet and how to create array from that string in the client ??
If you have the following Java class:
Then you can easily generate the data via the following using Gson:
The
jsonvariable will then have a value of[{"lastName": "Smith", "name": "John"},{"lastName": "Example", "name": "An"}].Then just send that as the response from your servlet, remember to set the content type of the request to
application/json.In order to get a handle on the data in JavaScript I would recommended using jQuery’s .getJSON() method, e.g.