Showing posts with label jackson json objectmapper. Show all posts
Showing posts with label jackson json objectmapper. Show all posts

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.