在带有Jersey的REST Web服务中返回JSON时,找不到媒体类型= application/json的MessageBodyWriter [英] MessageBodyWriter not found for media type=application/json when returning JSON in REST web service with Jersey
问题描述
我正在尝试使用Jersey创建一个非常简单的REST服务.这是服务代码
I am trying to create a very simple REST service using Jersey. Here is the service code
@Path("/UserService")
public class UserService {
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public List<User> getUsers() {
User user = new User(1, "Thomas", "Greene");
List<User> userList = new ArrayList<User>();
userList.add(user);
return userList;
}
}
当我通过Postman运行它时,它会返回一个XML响应
When I run it through Postman, it returns me a XML response
现在,我想返回一个JSON响应.因此,我将媒体类型更改为application/json
:
Now, I want to get a JSON response back. So, I changed the mediatype to application/json
:
@Path("/UserService")
public class UserService {
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers(){
User user = new User(1, "Thomas", "Greene");
List<User> userList = new ArrayList<User>();
userList.add(user);
return userList;
}
}
它在Tomcat日志中给我以下错误:
It gives me the below error in Tomcat logs:
严重:找不到媒体type = application/json,type = class java.util.ArrayList,genericType = java.util.List的MessageBodyWriter.
SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List.
有人可以指导我如何获取JSON响应吗?
Can someone please guide me how to get a JSON response back?
推荐答案
To use Jackson 2.x as your JSON provider you need to add jersey-media-json-jackson
module to your pom.xml
file:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.2</version>
</dependency>
然后注册 ResourceConfig
子类.
And then register the JacksonFeature
in your Application
/ResourceConfig
subclass.
有关更多详细信息,请查看Jersey 文档
For more details, have a look at Jersey documentation.
这篇关于在带有Jersey的REST Web服务中返回JSON时,找不到媒体类型= application/json的MessageBodyWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!