Spring MVC Rest / JSON Service

I just tried adding this to my sample controller:

@RequestMapping(value="/jsontest", method=RequestMethod.GET)
    public @ResponseBody User getUserAsJson() {

        User jsonUser = new User();
        jsonUser.setFirstName("Mickey");
        jsonUser.setLastName("Mouse");
        jsonUser.setUsername("mmous");


        return jsonUser;
    }

However, a visit to / jsontest url ends with a 406 error http => is not acceptable.

So ... what currently works to create "application / json" responses, instead of returning jsp / html views?

I am using Spring Framework 3.0.6 RELEASE.

+1
source share
2 answers

Add Jackson mapper to your CLASSPATH:

<dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.2</version>
</dependency>

And call your web service with the correct accept header, for example:

$ curl -H "Accept: application/json" localhost:8080/app/jsontest

Or using $.getJSON()from a browser.

+2
source
@RequestMapping(value="/jsontest", method=RequestMethod.GET,produces="application/json")
    public @ResponseBody User getUserAsJson() {

        User jsonUser = new User();
        jsonUser.setFirstName("Mickey");
        jsonUser.setLastName("Mouse");
        jsonUser.setUsername("mmous");


        return jsonUser;
    }

This should work. Add creates an attribute.

0

All Articles