MOXyJsonProvider不工作

时间:2017-04-08 22:44:55

标签: jersey jersey-2.0 glassfish-4 moxy

在我的REST应用程序中(在GlassFish 4.1.2下)我想将POJO转换为JSON并再次返回。这些例子都让它看起来很简单,但我遗漏了一些东西。

这是我的申请:

@ApplicationPath("/")
public class RootApp extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        HashSet set = new HashSet<Class<?>>();
        set.add(HelloWorld.class);
        return set;
    }

    @Override
    public Set<Object> getSingletons() {
        HashSet set = new HashSet<Object>();

        MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider();
        moxyJsonProvider.setFormattedOutput(true);
        set.add(moxyJsonProvider);

        return set;
    }
}

这是资源:

@Path("helloworld")
public class HelloWorld {

    private static int counter = 1;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getInevitableMessage() {    
        JsonHello hj = new JsonHello("Hello World", counter++);    
        return Response.ok(hj).build();
    }    
}

最后也是最不重要的是转换为JSON的POJO:

public class JsonHello {

    private int count;
    private String message;

    public JsonHello(String message, int count) {
        this.message = message;
        this.count = count;
    }

    public int count() { return count; }
    public void count(int value) { count = value; }

    public String message() { return message; }
    public void message(String value) { message = value; }
}

我指的是thread中标记的答案。当我尝试访问“/ helloworld”时,它会抛出以下异常:

org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper

如果资源只返回一个字符串,则此应用程序有效。 web.xml文件中没有任何内容,因为我让Glassfish通过其装饰器设置应用程序。

知道我在这里缺少什么吗?

1 个答案:

答案 0 :(得分:0)

I ended up solving the problem using the direction that @peeskillet suggested. MOXyJsonProvider is unneeded.

One problem that is hard to address is that almost all the examples on the web assume you are configuring your Servlet with a web.xml file, which I am not. All the configuration I do is from inside the Application object. The Jersey documentation does not make this very clear. What ends up working is this:

@Override
public Set<Class<?>> getClasses() {
    HashSet set = new HashSet<Class<?>>();
    set.add(JacksonFeature.class);
    set.add(MyObjectMapperProvider.class);
    set.add(Home.class);
    set.add(HelloWorld.class);
    return set;
}

At this point the REST resources can produce and consume various POJOs which are transcoded into JSON perfectly and without any effort.

Instead of just deleting this question I will put this answer here in hopes of saving someone the amount of time I spent finding this out.