简体   繁体   中英

getting “error Unsupported Media Type” while binding JSON data with spring mvc controller

I am capturing a hierarchical data using Jquery based Jstree library.Data is in a JSON format, I want to capture and bind this data to my bean class(JstreeJson.java).Here is what I have tried so far..

Ajax call :

 function getJSON() {       
              var jstree = $('#jstree1').jstree(true).get_json('#', {flat:true});
                console.log(JSON.stringify(jstree));
              $.ajax({          
                    type:"POST",
                    url:"createObjective",
                    data : { jstree: jstree },                      
                    dataType :"json", 
                    success : function(result) {
                        console.log(jstree);
                    console.log(result);
                 },
                 error: function(jqXHR, textStatus, errorThrown) {
                     console.log(jqXHR);
                     console.log(textStatus, errorThrown);
                 }
            }); 

         }

console.log output:

[{"id":"j1_1","text":"Simple root node","icon":true,"li_attr":{"id":"j1_1"},"a_attr":{"href":"#","id":"j1_1_anchor"},"state":{"loaded":true,"opened":false,"selected":false,"disabled":false},"data":{},"parent":"#"}]

controller

@RequestMapping(value="/createObjective",method=RequestMethod.POST)
public @ResponseBody String createObjective(@RequestBody JstreeJson jstree)
{
    System.out.println(jstree);
    return "done";
}

Bean class

public class JstreeJson
{
  private String id;
  private String text;
  private String parent;
   // getters and setter
 }

I have tried adding consumes and Headers but it didnt have any effect on my output

 @RequestMapping(value="/createObjective",method=RequestMethod.POST,consumes="application/json",headers = "content-type=application/x-www-form-urlencoded")

Try this @RequestMapping:-

@RequestMapping(value="/createObjective" method = RequestMethod.POST,consumes= {"application/json;charset=UTF-8"}, produces={"application/json;charset=UTF-8"})
public @ResponseBody String createObjective(@RequestBody JstreeJson jstree)
{
    System.out.println(jstree);
    return "done";
}

Or you can keep @RequestMapping simple as bellow:

@RequestMapping(value="/createObjective")

Spring will take care rest of the attributes of @RequestMapping depending on request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM