嵌入式Jetty的泽西岛-未找到MessageBodyWriter application/json [英] Jersey with embedded Jetty - MessageBodyWriter not found application/json
本文介绍了嵌入式Jetty的泽西岛-未找到MessageBodyWriter application/json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Jersey来将POJO作为JSON返回,但是出现以下错误:
I am attempting to return a POJO as JSON with Jersey, however I am getting the following error:
但是,当我运行该应用程序时,我得到:
However when I run up the application I get:
SEVERE: MessageBodyWriter not found for media type=application/json, type=class com.uk.jacob.model.Person, genericType=class com.uk.jacob.model.Person.
我有以下泽西岛资源
@Path("")
public class TestResponse {
@GET
@Path("hello")
@Produces(MediaType.APPLICATION_JSON)
public Response paramMethod() {
CacheControl control = new CacheControl();
control.setMaxAge(60);
Person jacob = new Person("Jacob");
return Response
.ok(jacob)
.cacheControl(control)
.build();
}
}
使用简单的Person POJO
With a simple Person POJO
public class Person {
private String firstName;
public Person(String firstName){
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
}
具有以下嵌入式Jetty配置
With the following embedded Jetty config
public static void main(String[] args) {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
context.setContextPath("/");
String webPort = System.getenv("PORT");
if(webPort == null || webPort.isEmpty()) {
webPort = "3000";
}
Server jettyServer = new Server(Integer.valueOf(webPort));
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "com.uk.jacob.api");
jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
正如您在上面看到的,我已启用POJOMappingFeature
As you can see above I have enabled the POJOMappingFeature
jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
推荐答案
POJOMappingFeature
用于泽西岛1.对于泽西岛2,您应该添加以下依赖项
POJOMappingFeature
is for Jersey 1. For Jersey 2 you should add the following dependency
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey2.version}</version>
</dependency>
并注册功能
jerseyServlet.setInitParameter(
"jersey.config.server.provider.classnames",
"org.glassfish.jersey.jackson.JacksonFeature");
这篇关于嵌入式Jetty的泽西岛-未找到MessageBodyWriter application/json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文