我正在尝试使用Jersey来将POJO作为JSON返回,但是出现以下错误:
但是,当我运行该应用程序时,我得到:
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();
}
}
用一个简单的人POJO
public class Person {
private String firstName;
public Person(String firstName){
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
}
使用以下嵌入式Jetty配置
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
jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
最佳答案
POJOMappingFeature
用于泽西岛1。对于泽西岛2,您应添加以下依赖项
<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");