Spring MVC Rest / JSON service

喜欢而已 提交于 2019-12-08 05:31:50

问题


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, visiting the /jsontest url ends on a 406 http error => not acceptable.

So... what's the currently working method for producing "application/json" responses, instead of returning jsp/html views?

I'm using Spring Framework 3.0.6 RELEASE.


回答1:


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 correct accept header, e.g.:

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

Or using $.getJSON() from browser.




回答2:


@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 produces attribute..



来源:https://stackoverflow.com/questions/8136926/spring-mvc-rest-json-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!