users@jersey.java.net

Polymorphic deserialization of JSON?

From: Chad McHenry <mchenryc_at_gmail.com>
Date: Sat, 9 May 2009 09:41:02 -0400

Is it possible to get JSONJAXBContext to recognize subclasses when
unmarshaling? My model has a discriminator (i.e. foo_type field below) to
determine subtype.
I added the Foo, FooBaz, and FooBar to the JAXBContext, and the 'retrieve'
method below, correctly serializes all of them.

I suspect it may involve writing a custom JAXBContext (or just an
Unmarshaller), but hope there is already a solution available. Any
suggestions on direction are welcome.

...Chad


class Foo {
    public int id;
    public String foo_type;
}
class FooBar extends Foo { public int bar; }
class FooBaz extends Foo { public String baz; }

====

@Path("/foo")
@Produces(MediaType.APPLICATION_JSON)
@Component
@Scope("singleton")
class FooResource {
    ...
    @GET
    @Path("/{id}")
    public Foo retrieve(@PathParam("id") Integer id) {...}

    /* Can the foo argument passed to this method be unmarshalled
     * as FooBar or FooBaz depending on the value of foo.foo_type? */
    @POST
    public Foo create(Foo foo) {...}
}

====

{"id":1, "foo_type":"foo_bar", "bar":33} => FooBar
{"id":2, "foo_type":"foo_baz", "baz":"hi"} => FooBaz