I have an object that I'd like to serve in JSON as a RESTful resource. I have Jersey's JSON POJO support turned on like so (in web.xml):
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
But when I try to access the resource, I get this exception:
SEVERE: A message body writer for Java type, class com.example.MyDto, and MIME media type, application/json, was not found
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException
...
The class that I'm trying to serve isn't complicated, all it's got are some public final fields and a constructor that sets all of them. The fields are all strings, primitives, classes similar to this one, or Lists thereof (I've tried using plain Lists instead of generic List<T>s, to no avail). Does anyone know what gives? Thanks!
Java EE 6
Jersey 1.1.5
GlassFish 3.0.1
Jersey-json has a JAXB implementation. The reason you're getting that exception is because you don't have a Provider registered, or more specifically a MessageBodyWriter. You need to register a proper context within your provider:
This looks up for an
@XmlRegistry
within the provided package name, which is a package that contains@XmlRootElement
annotated POJOs.then create an ObjectFactory in the same package:
With the
@Provider
registered, Jersey should facilitate the marshalling for you in your resource:This did it for me - Jersey 2.3.1
In the web.xml file :
In the pom.xml file :
Why are you using final fields? I'm using jersey and i have some JAXB objects/pojos and all i had to do was simply annotate my resource method with @Produces("application/json") and it works out of the box. I didn't have to mess with the web.xml. Just make sure your pojos are annotated correctly.
Here is a simple pojo
You've probably already figured this out, but all you need to do is add these jackson jars to your classpath: jackson-core, jackson-jaxrs, jackson-mapper, and jackson-xc
It appears that there is another way, as others have noted. Add this to your "com.sun.jersey.config.property.packages" parameter (if using tomcat and web.xml): "org.codehaus.jackson.jaxrs", like so:
Doing this will also require the same jackson jars on your classpath