Monday, August 3, 2009

Since many sites are offering JSON as an alternative to XML, and since JSON can be much more lightweight than XML, I started looking into Java JSON libraries. I wanted something fast and lightweight.

The JSON.org implementation is low-level and clunky, so I looked at gson and Jackson. One of the most obvious deficiencies of the JSON.org implementation is that it only deserializes from a String, and not from a Reader (or a Stream), which means the entire value has to be read into a String, and then parsed. I don't imagine that I'll be dealing with huge JSON values any time soon, but it is a concern. The other implementations do not have that deficiency and additionally provide a streaming or event API, which would be useful, should there be huge JSON values from which a small amount of data is of interest.

For the near term, I'll only be using the deserialization, and both of them seem fine. Jackson appears slightly bulkier than gson, in that it's broken into multiple jar files, which admittedly is a silly metric. I like the Jackson API a little better, though.

For serialization, I'm not satisfied with either one, but I like what Jackson offers better. gson serializes all the fields, including private fields. Jackson is close to what I want, in that it serializes POJOs, but it introspects the class from getClass(), rather than a passed in class, which is what I'd like to use to restrict which fields get serialized, which would allow having other public getters that aren't serialized that can be used in other code. Something like this

public <T> void serializeToJSON(Writer writer, T object, Class<T> type);

where the 3rd parameter would typically be an interface.

Update: serialization the way I want is in Jackson 1.2.

No comments:

Post a Comment