user2363971
user2363971

Reputation: 191

Post array of json objects to Spring MVC Controller

I have problems with sending and receiving a list of json objects (jQuery Ajax)

Java Object

public class UserSkill () {

 private long user;
 private long skill;
 private long level;

 //getter and setter methods

}

From Controller i get list of objects and it looks like this

$.getJSON("getList", function(data) {
    console.log(data);
});

//console log ->  [Object { user=4, skill=61, leve=10}, Object { user=3, skill=61, level=20}]

I changed some values and we have following code

ioarray = [];

//update methods

console.log(ioarray);

//console log ->  [Object { user=4, skill=61, level=9000 }, Object { user=3, skill=61, level=100 }]

Ajax POST

$.ajax({
    url : 'goUpdate',
    type : 'POST',
    contentType : 'application/json; charset=utf-8',
    dataType : 'json',
    data: ioarray,
    succcess : function(e) {
        alert('Yeah');
}

Controller

@RequestMapping(value = "goUpdate", method = RequestMethod.POST)
    public Object goUpdatePOST(@RequestBody List<UserSkill> list) {

        //list.get(0).getLevel(); 

        return list;
}

Logs

type Status report

message Request method 'POST' not supported

description The specified HTTP method is not allowed for the requested resource.

Something wrong here ... any ideas?

UPDATE;

Controler

@RequestMapping(value = "goUpdate", method = RequestMethod.POST)
public @ResponseBody String goUpdatePOST(@RequestBody UserSkill[] list) {

    for(UserSkill i : list) {
        System.out.println(i.getSkill());
    }
    return "somepage";

} 

jQuery

var ioarray = [{ user:4, skill:61, level:10}, 
{ user:3,  skill:61, level:20}];

        $.ajax({
            url : 'goUpdate',
            type : 'POST',
            data: JSON.stringify(ioarray),
        });

Console output

JSON
0
    Object { user=4, skill=61, level=10}

1
    Object { user=3, skill=61, level=20}

Source
[{"user":4,"skill":61,"level":10},{"user":3,"skill":61,"level":20}]

to pom.xml inserted jackson-mapper-asl and jackson-core-asl.

Of course this example generate same error... What i am doing wrong? I think I checked every possibility.

Upvotes: 0

Views: 6527

Answers (4)

TanvirChowdhury
TanvirChowdhury

Reputation: 2445

JS:

 $.ajax({
        type : "post",
        dataType : 'json', 
        url : 'addAdmin',  
        data : JSON.stringify(ioarray)
 })

Controller (note it takes a custom String only). Then it uses Jackson to parse the string manually, because Spring won't do it in this case. (Spring will only auto-parse if you're using @ModelAttribute form binding.)

@PostMapping("/addAdmin")
public boolean addAdmin(@RequestBody String json) throws Exception {

      String decodedJson = java.net.URLDecoder.decode(json, "UTF-8");
      ObjectMapper jacksonObjectMapper = new ObjectMapper(); // This is Jackson
      List<UserRolesGUIBean> userRolesGUIBeans =  jacksonObjectMapper.readValue(
              decodedJson, new TypeReference<List<UserRolesGUIBean>>(){});
      // Now I have my list of beans populated.
}

Upvotes: 0

Ankur Singhal
Ankur Singhal

Reputation: 26077

does this works for you

    $.ajax({
        url : 'goUpdate',
        type : 'POST',
        data: JSON.stringify(ioarray),
        dataType: "json",
        contentType: "application/json"
    });

Upvotes: 2

Yagnesh Agola
Yagnesh Agola

Reputation: 4659

I got same problem i didn't find any solution at last i have find another solution using simple HttpServletRequest.
You may use HttpServletRequest to read request data and use JSON API to convert this json String into List<UserSkill> object. You may use GSON API for converting your json string into list .

For this you need following changed in controller class method as shown below :

@RequestMapping(value = "goUpdate", method = RequestMethod.POST)
public @ResponseBody String goUpdatePOST(HttpServletRequest request) 
{
    String jsonStr = IOUtils.toString(request.getInputStream());
    Gson gson = new Gson();
    Type  fooType = new TypeToken<List<UserSkill>>() {}.getType();
    List<UserSkill> list = gson.fromJson(jsonStr,fooType);
    return gson.toJson(list);
}  

In response send JSON string which can be created by converting List<UserSkill> into JSON string using Gson API.

May this will help you.

Upvotes: 0

franki3xe
franki3xe

Reputation: 330

try to use value = "/goUpdate"

@RequestMapping(value = "/goUpdate", method = RequestMethod.POST)

Upvotes: 0

Related Questions