使用 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?
推荐答案
要使用 Jackson 2.x 作为 JSON 提供程序,您需要添加 jersey-media-json-jackson
模块到你的 pom.xml
文件:
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>
然后注册JacksonFeature
在您的 应用程序
/ResourceConfig
子类.
And then register the JacksonFeature
in your Application
/ResourceConfig
subclass.
有关更多详细信息,请查看泽西岛 文档.
For more details, have a look at Jersey documentation.
这篇关于使用 Jersey 在 REST Web 服务中返回 JSON 时,找不到媒体类型 = application/json 的 MessageBodyWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!