Question

Im trying to pass an array from javascript to java servlet using Jackson, how this can be done..thanks

Was it helpful?

Solution

The basic idea should be straightforward:

Server:

doPost(HttpServletRequest req, HttpServletResponse resp)
{
  ObjectMapper mapper = new ObjectMapper();
  ArrayNode rootNode = mapper.readValue(req.getReader(), ArrayNode.class);
}

Client:

Using jQuery (you can also do it with other frameworks, or manually). Load a copy of json2.js to make sure you have JSON.stringify.

jQuery.ajax({
  type: 'POST',
  url: servletURL,
  data: JSON.stringify(jsArray),
  dataType: 'json',
  contentType: 'application/json'
});

OTHER TIPS

For passing the array from the browser to the server side you don't need Jackson. You just need Ajax. For example, using jQuery you can do it this way:

$.ajax({
  url: 'your servlet url',
  data: yourArray
});

Then on the server side, you might want to deserialize the JSON into a JavaBean or, in your case, a java.util.List using Jackson. You can do that this way:

ObjectMapper mapper = new ObjectMapper();
List array = mapper.readValue(jsonText, List.class);

Where jsonText contains the String representation of yourArray that is sent to the server-side from the browser.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top