Jackson JSON serialization, recursion avoidance by level defining
I recently encountered a similar problem: Jackson - serialization of entities with birectional relationships (avoiding cycles)
So the solution is to upgrade to Jackson 2.0, and add to classes the following annotation:
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class,
property = "@id")
public class SomeEntityClass ...
This works perfectly.
Check the following links, it might help :
- http://wiki.fasterxml.com/JacksonFeatureBiDirReferences
- How to solve circular reference in json serializer caused by hibernate bidirectional mapping?
The only option after that would be to create your own custom module for serialization/deserialisation for your object type. see here:
- http://wiki.fasterxml.com/JacksonHowToCustomSerializers
- http://wiki.fasterxml.com/JacksonHowToCustomDeserializers
Regards.
There is no support for level-based ignorals.
But you can get Jackson to handle cyclic references with 2.0, see for example "Jackson 2.0 released" for explanation on how to use @JsonIdentityInfo
.
If you want to limit yourself to only one level (ie : you go to the children of the current object and not further), there is a simple solution with @JsonView.
On every field that is a link to another object, annotate it with the current class as your view :
class A {
private int id;
@JsonView(A.class) private B b;
constructors...
getters and setters
}
class B {
private int ind;
@JsonView(B.class) private A a;
constructors...
getters and setters
}
Then, when serializing, use the object class as your view. Serializing an instance of A would render something like that :
{
id: 42,
b: {
id: 813
}
}
Make sure the DEFAULT_VIEW_INCLUSION is set to true, or the fields without a @JsonView annotation will not be rendered. Alternatively, you can annotate all other fields with @JsonView using the Object class, or any common super-class :
class A {
@JsonView(Object.class) private int id;
@JsonView(A.class) private B b;
constructors...
getters and setters
}