kamaci
kamaci

Reputation: 75167

How to unmarshall a JSON object to a Java Class?

I have Spring REST application that can marshall an object to JSON when a GET request occurs. However what should I do for POST methods. I send a JSON object but it can't unmarshall it into a Java object. Here is a method of my controller:

@RequestMapping(value = "/user", method = RequestMethod.POST)
public void createUser(HttpServletResponse response, @RequestBody User user) { 
   ...
    response.setStatus(HttpServletResponse.SC_OK);
}

I send my JSON like that:

        var userName = $('#userName').val();
        var password = $('#password').val();
        var mail = $('#mail').val();
        var admin = $("#admin").is(':checked');
        var user = {userName: userName, password: password, mail: mail, admin:admin};
        $.ajax({
            async : false,
            type: 'POST',
            contentType: 'application/json',
            url: '/sfd/user',
            data: user,
            dataType: 'json',
            success: function(data) {
               ...
            },
            error: function(data) {
                ...
            }
        });

PS: Here: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/ it says:

If there are validation errors, a HTTP 400 is returned with the error messages, otherwise a HTTP 200 is returned.

I have 400 Bad Request Error. Maybe the problem is related to that?

PS2: Should I send User object after I set all its elements? I mean User object has some other attributes, i.e. address but I don't set and send it from client.

PS3: When I debug AbstractHandlerExceptionResolver's resolveException method I see that error. It says 'u' is undefined character(I tested it that 'u' is the first key of JSON => userName's first character).

Upvotes: 2

Views: 4050

Answers (2)

geez
geez

Reputation: 106

In the @RequestMapping set headers to accept application/json, and then try configuring this in your application context

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:order="1">
<property name="mediaTypes">
    <map>
        <entry key="json" value="application/json" />
    </map>
</property>

<property name="defaultViews">
    <list>
        <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
    </list>
</property>
</bean>

Upvotes: 0

danny.lesnik
danny.lesnik

Reputation: 18639

You should have the following setting in your XML:

<context:annotation-config/> 

and then to make sure that jackson jar is in your classpath:

in my projects I prefer to set it as Spring Bean:

it will deserialize your json data to object.

You can read it more about it here:

http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

Upvotes: 2

Related Questions