views:

289

answers:

2

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

A: 

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.

Bytecode Ninja
Your client code sends the data in query-string format, not JSON.
Matthew Flaschen
+1  A: 

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'
});
Matthew Flaschen
thanks matthew for reply...im using YUI 3, the array reach servlet and everything is ok, but i need to get the right parameter from request.i replaced req.getReader() with req.getParameter("myArray") but still not working
Mohammed_Q
nevermind...its worked i used req.getParameterValues("myArray"), thanks for helping
Mohammed_Q
@Mohammed, if you're using `getParameterValues`, you're probably not using JSON. You most likely have a regular GET query-string.
Matthew Flaschen
i thought its worked...im using Jackson.so is there away to pick specific parameter from HttpServletRequest using ArrayNode rootNode = mapper.readValue(req.getReader(), ArrayNode.class);??
Mohammed_Q
Okay, it looks like you do need both `getParameterValues` and Jackson because of the way YUI is sending the request.
Matthew Flaschen