Jersey with embedded Jetty - MessageBodyWriter not found application/json

丶灬走出姿态 提交于 2019-12-25 07:55:03

问题


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.

I have the following Jersey resource

@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();
    }
}

With a simple Person POJO

public class Person {
    private String firstName;

    public Person(String firstName){
        this.firstName = firstName;
    }

    public String getFirstName(){
        return firstName;
    }
}

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();
        }
    }

As you can see above I have enabled the POJOMappingFeature

    jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");

回答1:


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>

and register the feature

jerseyServlet.setInitParameter(
        "jersey.config.server.provider.classnames",
        "org.glassfish.jersey.jackson.JacksonFeature");


来源:https://stackoverflow.com/questions/39559432/jersey-with-embedded-jetty-messagebodywriter-not-found-application-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!