Thursday, August 20, 2009

Jackson JSON Processor

The Jackson JSON Processor is used for marshalling and unmarshaling JSON strings. It is capable of converting JSON strings into Java objects and vice versa. THis biderctional conversion simplifies passing information between java classes and javascript code. Other processors exist, such as XStream, that marshal and unmarshal XML and JSON. The Jackson JSON Processor is by far the fastest one out there.

Using Java Beans

Code examples based ion release 0.98.

When working with Java Beans, the following restrictions are used by the Jackson JSON Processor. The bean has an empty public constructor, methods exposed follow the set/get/is construct, and the class CANNOT be an inner class.

Construcitng a bean and exporting it via an ObjectMapper is the preferred approach. With proper planning, you might not even need to copy information into the target Java Bean for transformation.

Code sample to generate JSON form a java bean.

ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
mapper.writeValue(sw, myDS);
String testStr = sw.toString();
System.out.println("json Bef3 [" + testStr + "]");

Code sample to unmarshal JSON into a java bean.
ObjectMapper mapper = new ObjectMapper();
DailySchedule sample = mapper.readValue(testStr, DailySchedule.class);

The same ObjectMapper may be used.

1 comment:

  1. Actually it is perfectly fine to be an inner class, but it can not be NON-static inner class. This because non-static inner classes do not (and can not) have zero-argument constructor -- a "hidden this pointer" (parent reference) must be passed, and compiler creates this constructor.
    Jackson can not make use of this constructor.

    So just make sure your inner class has 'static' in its declaration and you are good to go.