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

Smita Ahinave
  • 1,901
  • 7
  • 23
  • 42
user2006369
  • 11
  • 1
  • 1
  • 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? – Gunslinger Aug 01 '13 at 07:49
  • Possible duplicate of [Deserializing json array in Spring MVC controller](http://stackoverflow.com/questions/27613613/deserializing-json-array-in-spring-mvc-controller) – Andrei Epure Mar 23 '17 at 10:18

2 Answers2

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.

Community
  • 1
  • 1
qkrijger
  • 26,686
  • 6
  • 36
  • 37
  • 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 05 '13 at 10:44
  • Controller: @RequestMapping(value = "/createcontactuspage.htm", method = RequestMethod.POST) public String createContactUsPage(@RequestBody ArrayList 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 05 '13 at 10:46
  • I don't think `@RequestBody ArrayList input` will work. Try making an class `Contacts` containing an `ArrayList` 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 05 '13 at 11:38
  • Am still getting same error after changing it to as you said. – user2006369 Aug 05 '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 05 '13 at 16:10
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;
}

}