2

I'm requesting data from controller through ajax, but it can't convert json object to java object. I'm using jackson 2.2.3 and Spring 4.0.0. Could you help me find out where I did wrong? Thanks.

part of 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 request:

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);
    }
}
);

controller:

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

public String batchAdd(@RequestBody Classification c){

    return "failure";
}

Classification.java

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

if i change the controller method to

public String batchAdd(@RequestBody String cla){

        return "failure";
    }

it work fine, and I can get the json string. Did anyone else meet this question before?

1 Answer 1

1

You may need to JSON.stringify() your data before posting it to the endpoint:

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

Here is some additional info on stringify. Depending on which browsers you need to support, you may also want to read this

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Matt. In fact, I tried this before but didn't work. And finally I mapped the json data by myself using com.fasterxml.jackson.databind.ObjectMapper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.