【问题标题】:Spring MVC with ajax request带有ajax请求的Spring MVC
【发布时间】:2014-03-07 11:30:48
【问题描述】:

我正在通过 ajax 从控制器请求数据,但它无法将 json 对象转换为 java 对象。我正在使用杰克逊 2.2.3 和 Spring 4.0.0。你能帮我找出我哪里做错了吗?谢谢。

epscms-servlet.xml 的一部分:

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
           <property name= "messageConverters" >
             <list>
                 <ref bean="jacksonMessageConverter" />
             </list>
        </property>
</bean>

ajax 请求:

var data = {
        orderId:1,
        parentId:0,
        className:"test",
        newsType:1
    }; 
$.ajax({
    url : "${pageContext.request.contextPath}/classification/add/batch",
    type : "POST",
    data : data,
    dataType: "json",
        contentType: 'application/json', 
    success : function(data) {
        alert("success");
    },
    error : function(data, status){
        alert(data + status);
    }
}
);

控制器:

@RequestMapping(value="/add/batch", method=RequestMethod.POST,    consumes=MediaType.APPLICATION_JSON_VALUE)

public String batchAdd(@RequestBody Classification c){

    return "failure";
}

分类.java

public class Classification {
    private int orderId;
    private String className;
    private int parentId;
    private int newsType;
    //getters and setters..
}

如果我将控制器方法更改为

public String batchAdd(@RequestBody String cla){

        return "failure";
    }

它工作正常,我可以得到 json 字符串。以前有没有其他人遇到过这个问题?

【问题讨论】:

    标签: ajax spring-mvc jackson


    【解决方案1】:

    在将数据发布到端点之前,您可能需要 JSON.stringify():

    ...
    type : "POST",
    data : JSON.stringify(data),
    dataType: "json",
    ...
    

    这里有一些关于 stringify 的 additional info。根据您需要支持的浏览器,您可能还想read this

    【讨论】:

    • 谢谢马特。事实上,我以前试过这个,但没有奏效。最后我自己使用com.fasterxml.jackson.databind.ObjectMapper映射了json数据。
    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 2017-10-21
    • 2016-11-28
    • 2015-08-08
    • 2015-04-28
    • 1970-01-01
    • 2012-05-30
    • 2014-04-01
    相关资源
    最近更新 更多