JSON加Spring MVC 3.2错误415(不支持的媒体类型)


问题内容

我做错什么了?我尝试使用Spring
mvc和JSON。当我尝试调试我的代码时,我正在寻找javascript有效但不能正常工作的控制器。在浏览器中,我收到错误415不支持的媒体类型。

脚本:

$(document).ready(function() {
  $('#newSmartphoneForm').submit(function(event) {

      var producer = $('#producer').val();
      var model = $('#model').val();
      var price = $('#price').val();
      var json = { "producer" : producer, "model" : model, "price": price};

    $.ajax({
        url: $("#newSmartphoneForm").attr( "action"),
        data: JSON.stringify(json),
        type: "POST",

        beforeSend: function(xhr) {
            xhr.setRequestHeader("Accept", "application/json");
            xhr.setRequestHeader("Content-Type", "application/json");
        },
        success: function(smartphone) {
            var respContent = "";

            respContent += "<span class='success'>Smartphone was    created: [";
            respContent += smartphone.producer + " : ";
            respContent += smartphone.model + " : " ;
            respContent += smartphone.price + "]</span>";

            $("#sPhoneFromResponse").html(respContent);         
        }
    });

    event.preventDefault();
  });

});

控制器:

   @RequestMapping(value="/create", method=RequestMethod.POST, 
        produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {
    return smartphoneService.create(smartphone);
}

问题答案:

这可能是因为在运行时您的类路径中没有Jackson。

错误消息指出服务器由于某种原因无法处理您的JSON请求。JSON通过称为 消息转换器 的东西转换为Java对象。如果您<mvc:annotation- driven />在Spring XML配置中(或启用了Java配置),则会自动注册JSON消息转换器。如果没有,则必须注册。