Feature: Unwrapping of POJOs in JSON
(see Jira entry JACKSON-132 for details)
Problem to Solve
Sometimes structure of JSON is flat, compared to ideal structure of Java objects.
For example, consider following Java definition:
class Place {
public String name;
public Location location;
}
class Location {
public int latitude, longitude;
}which we would like to bind to (or from) JSON like:
{
"name" : "home",
"latitude" : 127,
"longitude" : 345
}
Solution
With earlier Jackson versions, this mapping would only have succeeded by custom handling; but with the new feature we can simply add an annotation:
class Place {
public String name;
@JsonUnwrapped public Location location;
}to indicate that properties within Location object of 'location' property are to be serialized as properties of its parent Object; and when deserializing, conversely they need to be extracted from parent JSON Object and used to construct Location object.
2.0 improvements
In addition to base functionality, Jackson 2.0 also added two new properties, "prefix" and "suffix", which can be used for basic namespacing:
class Point {
int x, y;
}
class TwoPoints {
@JsonUnwrapped(prefix="p1") public Point point1;
@JsonUnwrapped(prefix="p2") public Point point2;
}which would be serialized as
{
"p1.x" : 1,
"p1.y" : 2,
"p2.x" : 3,
"p2.y" : 4
}This feature can be used to both avoid conflicts, and to handle virtual hierarchies (like binding Java Properties that use dotted-names to indicate hierarchy).
