In my REST applications (under GlassFish 4.1.2) I want to convert POJOs to JSON and back again. The examples all make it look easy but I am missing something.
Here is my application:
@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;
}
}
And here is the Resource:
@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();
}
}
And last and least is the POJO to convert to and from JSON:
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; }
}
I am referring to the tagged answer in this thread. When I attempt to access "/helloworld" it pitches the following exception:
org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
This application works if the resource just returns a string. There is nothing in the web.xml file since I am letting Glassfish set the application via its decorators.
Any idea what I am missing here?
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.