Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Am working on spring mvc and i need to pass JSON array to spring controller from my jsp using ajax. Can anyone help me out how to pass, map and access JSON array in controller.

(JSON array would be like [{'Name':'ksjdfh','Email':'sdfkhg'},{'Name':'ksjdfh','Email':'sdfkhg'},{'Name':'ksjdfh','Email':'sdfkhg'}])

Thanks in Advance

share|improve this question
 
What it the problem, do you want automatic deserialization? Is it enough to take the json as a String param and deserialize it yourself? –  Gunslinger Aug 1 '13 at 7:49
add comment

1 Answer

There is a post on how to do that here: Parsing JSON in Spring MVC using Jackson JSON.

Basically, you need a model object to deserialize the JSON to.

Note that (as Gunslinger says) you could also just pass the JSON as string as you would any other parameter. In a GET request that would result in an URL (without use of cookies) like localhost/foo?bar=[your_json_as_string]

Also note that you are using AJAX is not at all essential to your problem.

share|improve this answer
 
I submitted the form but am geeting 415 The server refused this request because the request entity is in a format not supported by the requested resource for the requested method () error. My code would be like JSP: document.contact.action = "createcontactuspage.htm"; document.contact.method = "POST"; document.contact.submit(); –  user2006369 Aug 5 '13 at 10:44
 
Controller: @RequestMapping(value = "/createcontactuspage.htm", method = RequestMethod.POST) public String createContactUsPage(@RequestBody ArrayList<Contact> input, BindingResult result, ModelMap model, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ScanSeeServiceException {for(Contact contact : input){ System.out.println(contact.getContactEmail());} return input.toString();} –  user2006369 Aug 5 '13 at 10:46
 
I don't think @RequestBody ArrayList<Contact> input will work. Try making an class Contacts containing an ArrayList<Contact> and in the controller @RequestBody Contacts input. Also, make sure that Jackson understands what you supply and is able to map it by writing unit tests that convert to an object from the json string. –  qkrijger Aug 5 '13 at 11:38
 
Am still getting same error after changing it to as you said. –  user2006369 Aug 5 '13 at 12:38
 
Then please update your question with your unit test and your controller code. Btw, now that I think of it, I don't know if @RequestBody is the right annotation here. I would use @RequestParam(value = "bar") in the case if you pass it in the query string –  qkrijger Aug 5 '13 at 16:10
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.