I use Jackson library for serialization of my pojo objects into JSON
representation.
For example I have class A and class B:
class A {
privat
Check the following links, it might help :
The only option after that would be to create your own custom module for serialization/deserialisation for your object type. see here:
Regards.
For depth wise serialization, you can refer to example here https://github.com/abid-khan/depth-wise-json-serializer
For some cases you can limit serialization depth using a thread local integer holding max depth. See this answer.
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
}
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
.
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.