我有一个非常简单的对象,我想以JSON
的形式返回public class Event {
private String store;
private Date date;
private double fee;
private String kit;
private String information;
和测试控制器如下
@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;
}
}
我得到"此请求标识的资源只能生成具有根据请求不可接受的特征的响应"接受"报头"
我的servlet只有这个条目
<mvc:annotation-driven />
如何实现所需的输出?
答案 0 :(得分:2)
加
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>
答案 1 :(得分:-1)
我猜它是内容协商的问题。 &#34;接受&#34;的价值是什么?你的请求中的标题?它可能被设置为除了&#34; applcation / json&#34;之外的其他东西,但由于&#34;接受&#34;标题值为&#34; * / *&#34;此控制器方法仍然注册为请求处理程序。例如&#34;接受:text / xml&#34 ;;
我建议你尝试的另一件事是返回ResponseEntity而不是Event。它将使用HttpMessageConverters转换您的响应(默认情况下,gson用作json类型内容的解析器,如果Jackson存在于您的类路径中,则将使用它)。您可以阅读更多here