users@jersey.java.net

Native JSON binding using JacksonJsonProvider

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Tue, 3 Mar 2009 23:41:21 -0800

I wrote a simple provider that uses Jackson Json processor
(http://jackson.codehaus.org) to implement true Json mappings for
JAX-RS implementations, and it seems to work quite nicely with Jersey.
So I thought it might be useful for others as well.

Provider itself is just a single class
(https://svn.codehaus.org/jackson/trunk/src/jaxrs/java/org/codehaus/jackson/jaxrs/JacksonJsonProvider.java),
but is packaged as a separate jar (->
[http://jackson.codehaus.org/Download) so that it can be plugged in
easily.

In addition to adding the jars (jackson core, mapper for data binding,
and the provider jar), it has to be registered using the usual
mechanism (can be added as a singleton, holds no real state),
something like:

--
import java.util.*;
import javax.ws.rs.core.*;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
public final class RestApplication
    extends Application
{
    // Best to register as a singleton to allow reuse of ObjectMapper:
    public Set<Object> getSingletons()
    {
        HashSet<Object> singletons = new HashSet<Object>();
        singletons.add(new JacksonJsonProvider());
        return singletons;
    }
}
---
(which I deploy using Jersey-provided ServletContainer, and run on
Jetty -- so should work in about any combination)
Doing this let's all the usual annotation-based stuff work for the
registered content type ("application/json").
So why use this over mapped/badgerfish conventions and JAXB? To get
sensible binding between Json and Objects. And perhaps also to improve
speed by factor of 3x - 5x, if that matters. :-)
Type support covers basic JDK types as well as beans (setters needed
for deserialization, getters for serialization); for more information
you can check out Jackson tutorial
([http://jackson.codehaus.org/Tutorial]).
Anyway -- if you are using Jersey with Json, this might be worth
checking out. And if so, please let me know how things go.
Also: since I am not a JAX-RS expert, there are probably better ways
to do integration, so I appreciate any improvements to the provider
itself.
-+ Tatu +-