简体   繁体   中英

Return POJO as JSON in Spring MVC 4

I have a very simple object, that i want to return as 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."

My servlet has only this entry

<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? 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. For example "Accept:text/xml";

Other thing I would suggest you to try is to return ResponseEntity instead of 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). You can read more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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