1

I 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'}])

2
  • What it the problem, do you want automatic deserialization? Is it enough to take the json as a String param and deserialize it yourself? Commented Aug 1, 2013 at 7:49
  • Possible duplicate of Deserializing json array in Spring MVC controller Commented Mar 23, 2017 at 10:18

2 Answers 2

0

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.

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

5 Comments

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();
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();}
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.
Am still getting same error after changing it to as you said.
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
0

This is my solution:

js class that we want to send:

 function Event(id, name) {
this.starttime = '';
this.endtime = '';
this.shiftUsers = [];
this.name = name
this.id = id;

}

After that fill array:

var shifts = [];
shifts.push(new Event(newid, current_name));

Ajax part:

$(document).on('click', '#test1', function(e) {

console.log('Test ajax save');
$.ajax({
    headers: {
        "Accept": "application/json",
        "Content-Type": "application/json"
    },
    type: "POST",
    url: "ajaxCreateShiftKind2.htm",
    dataType: "json",
    data: JSON.stringify(shifts),
    contentType: 'application/json',
    success: function(html) {
        alert(html);
    }
});

});

And java part, recive:

 @RequestMapping(value = "/ajaxCreateShiftKind2", method = RequestMethod.POST)
public @ResponseBody
Map<String, Object> ajaxCreateShiftKind2(HttpServletRequest request) {

    Map<String, Object> myModel = new HashMap<String, Object>();

    //org.codehaus.jackson.map.ObjectMapper 
    ObjectMapper om = new ObjectMapper();

    //Input input = mapper.readValue( request.getInputStream() , Class Input... ); 
    Event[] se;
    try {
        se = om.readValue(request.getInputStream(), Event[].class);
    } catch (Exception e) {
        se = null;
    }

    myModel.put("ajaxResult", 1);
    myModel.put("ajaxMessage", "Added succesful");
    myModel.put("ajaxShiftKind", "Hello world!");
    myModel.put("ajaxData", se);
    return myModel;
}

And class that we expect from js, setters and getters are necessary:

public class Event {

int id;
String name, endtime, starttime;
int[] shiftUsers;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getStarttime() {
    return starttime;
}

public void setStarttime(String Starttime) {
    this.starttime = Starttime;
}

public String getEndtime() {
    return endtime;
}

public void setEndtime(String Endtime) {
    this.endtime = Endtime;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public void setShiftUsers(int[] shiftUsers) {
    this.shiftUsers = shiftUsers;
}

public int[] getShiftUsers() {
    return this.shiftUsers;
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.