users@jersey.java.net

Re: [Jersey] Unmarshalling List of strings

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Tue, 30 Jun 2009 15:21:41 -0700

On Tue, Jun 30, 2009 at 1:50 AM, Marko
Novakovic<mnovakovic.fon_at_gmail.com> wrote:
> Hi,
>
> I have managed to unmarshall list of JAXB-annotated objects from JSON using
> technique described in some of the earlier posts(Bu using providers etc...).
> However, how can i unmarshall list of Strings or Integers. For example
> ["string1", "string2"] to List<String>. I would like to stay in JSON-XML
> independent mode.

If by independent you mean straight-forward json, Jackson would work
like Paul mentioned.
For that you need jackson-jaxrs jar (which has JSON provider), and
just need to register the class as a singleton (from jax-rs
Application class, or from web.xml), just like any other providers
that are not auto-registered by Jersey.

For example, I sometimes do (code copied from
[http://www.cowtowncoder.com/blog/archives/2009/03/entry_229.html]):
---
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;
    }
}
---
Given that, the usual mapping works like expected: String[] and
List<String> work (actually even untyped 'List' happens to work since
String is untyped equivalent for Object) without any special
considerations. You only need the usual JAX-RS annotations to indicate
path bindings and such. No root annotation is needed (xml requires
@XmlRootElement to know root element name) either.
Using Jackson provider does not affect xml side at all (so json and
xml can peacefully co-exist), but it will have preference over mapped
json conventions.
Hope this helps,
-+ Tatu +-