Feature: Define actual type of Root Object (for serialization)

(see Jira entry JACKSON-195 for more details)

Whereas defining type of the root object during serialization is mandatory and explicit, prior to Jackson 1.5, there was no way to force nominal type of serialized root object: type was always taken to be the actual runtime type.

This feature simply means that it is possible to override this type detection, by defining which type should be used for serialization purposes. Type has to be a super type of actual value (or type itself) -- this is obvious, but worth mentioning; it will be verified and if an incompatible type is used, exception thrown.

Without further ado, let's consider a case of type MyBean, which is an interface, and MyBeanImpl that implements it. With 1.5, you can serialize an instance as MyBean (possibly ignoring auto-detectable properties MyBeanImpl would have):

ObjectMapper mapper = new ObjectMapper();
MyBeanImpl instance = new MyBeanImpl();
String json = mapper.typedWriter(MyBean.class).writeValueAsString();

which does what is expected.

ObjectWriter? What's that?

Ok, so the most interesting thing with code above is the new 1.5-only type ObjectWriter. What is it?

It is a builder object (specifically, of fluent interface kind) to be used for building actual writers with specified per-instance configuration. But why separate interface beyond ObjectMapper? Because of two issues:

Using Fluent Interface is a somewhat elegant solution: resulting writers are always immutable (new instance is created for different configuration settings), lightweight, and only have fixed set of write methods; one that is not dependant on number of configurable settings. So going forward, it should be much simpler to add new per-serialization settings if and as need be: for example, version number to use for filtering.


CategoryJackson

JacksonFeatureRootType (last edited 2010-03-13 00:16:00 by TatuSaloranta)

Copyright ©2009 FasterXML, LLC