泽西与嵌入式Jetty - MessageBodyWriter找不到application / json

时间:2016-09-18 15:36:56

标签: java json jersey

我正在尝试使用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");

1 个答案:

答案 0 :(得分:3)

POJOMappingFeature适用于Jersey 1.对于Jersey 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");