users@jersey.java.net

Re: [Jersey] Bug in Null handling in JSON/JAXB ?

From: DirkM <dirk_at_olx.com>
Date: Tue, 25 Aug 2009 16:26:07 -0500 (CDT)

I hope this post didn't get sent multiple times, nabble appears to be having
some issues.


Jalpesh Patadia wrote:
>
> Basically I have some POJO fields which are defined with the @XmlElement
> element as follows :
>
> @XmlElement(nillable = true) private String status;
>
> Now, when I display the output as application/xml - I get the correct
> value :
>
> <status xsi:nil="true"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
>
> However when I use application/json as the output I get :
>
> "status" : {
> "@nil" : "true"
> }
>
> Which seems incorrect. According to the JSON spec, it be more like :
>
> "status" : null
>

I was having a similar problem, and decided to use
http://code.google.com/p/google-gson/ GSON to handle writing JSON for
Jersey. It outputs nulls more intuitively than JAXB, which is constrained by
having originally been designed for XML.

You will need to configure it to output nulls instead of ignoring those
fields that are null:
http://sites.google.com/site/gson/gson-user-guide#TOC-Null-Object-Support

A second advantage is that GSON makes more assumptions about the classes
that it is encoding, so most of the time you don't actually need to annotate
them at all. Great if you're using classes that are in a library you didn't
write yourself.

In order to make Jersey write JSON using a custom writer, you need to create
a Provider that implements MessageBodyWriter. I've included my version
below. Note that I'm using Guice, so there are some extra annotations and
Gson gets injected (the configuration changes I suggested above are set up
on the injected class, not within this class)

@Provider
@Produces(MediaType.APPLICATION_JSON)
@Singleton
public final class JSONWriter implements MessageBodyWriter {
    private Gson gson;

    @Inject
    public JSONWriter(Gson gson) {
        this.gson = gson;
    }

    @Override
    public long getSize(Object t, Class type, Type genericType, Annotation[]
annotations,
            MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(Object t, Class type, Type genericType, Annotation[]
annotations,
            MediaType mediaType, MultivaluedMap httpHeaders, OutputStream
entityStream)
            throws IOException, WebApplicationException {
        entityStream.write(gson.toJson(t).getBytes());

    }

    @Override
    public boolean isWriteable(Class type, Type genericType, Annotation[]
annotations,
            MediaType mediaType) {
        return true;
    }

}


-- 
View this message in context: http://n2.nabble.com/Bug-in-Null-handling-in-JSON-JAXB-tp2996191p3512720.html
Sent from the Jersey mailing list archive at Nabble.com.