简体   繁体   English

在Spring MVC 4中将POJO作为JSON返回

[英]Return POJO as JSON in Spring MVC 4

I have a very simple object, that i want to return as JSON 我有一个非常简单的对象,我想以JSON的形式返回

public class Event {

    private String store;
    private Date date;
    private double fee;
    private String kit;
    private String information;

and a test controller as follows 和测试控制器如下

@RestController
@EnableWebMvc
public class UserController {

    @RequestMapping(value = "/user/{username}", method = RequestMethod.GET, produces = "application/json", headers="Accept=*/*")
    @ResponseBody
    public Event getUser(@PathVariable("username") String username){

        Event event = new Event("dummy", new Date(), 4.0, "dummy", "dummy");
        return event;
    }

}

I get "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers." 我得到“此请求标识的资源只能根据请求“ accept”标头生成特性不可接受的响应。”

My servlet has only this entry 我的servlet只有此条目

<mvc:annotation-driven />    

How can i achieve the desired output? 如何获得所需的输出?

Added 添加

dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.7.0</version>
    </dependency>

My guess its the issue with content negotiation. 我猜这是内容协商的问题。 What is the value of the "Accept" header in your request? 您的请求中“ Accept”标头的值是什么? It may be that it is set to something else than "applcation/json", but due to "Accept" header value being "* / *" this controller method is still registered as request handler. 可能将其设置为除“ applcation / json”以外的其他值,但是由于“ Accept”标头值为“ * / *”,因此该控制器方法仍注册为请求处理程序。 For example "Accept:text/xml"; 例如“ Accept:text / xml”;

Other thing I would suggest you to try is to return ResponseEntity instead of Event . 我建议您尝试的另一件事是返回ResponseEntity而不是Event。 It will convert your response using HttpMessageConverters (by default gson is being used as parser for json type content, if Jackson exists in you class path it will be used instead). 它将使用HttpMessageConverters转换您的响应(默认情况下,gson用作json类型内容的解析器,如果您的类路径中存在Jackson,则将使用它代替)。 You can read more here 你可以在这里阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM