I have a class Foo which have reference to itself. This is rough example of situation I have been in.
@Entity
public class Foo() {
@Column(name = "id", unique = true, nullable = false)
private Long id;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_Foo")
private Foo parent;
}
When i pass Foo object to JSON response generator, all required getters are initiated and all required data retrieved from DB by JPA.
Now the problem is that if i remove @JsonIgnore from self-reference field I'm getting parent info, and parent parent info and etc.
What I want is that I could limit deep of retrieved parent info. For example.:
- Deep 0 - I will get only Foo data
- Deep 1 - I will get data of Foo and Foo parent
- Deep 2 - I will get data of Foo and Foo parent and Foo parent parent etc.
Maybe there is a simple solution with annotations or smth, because i couldn't find anything.
EDIT:
Solved this problem with custom serializer and some recursion magic.
private void serializeParents(JsonGenerator gen, Foo value, int currentDepth) {
if (currentDepth < PARENTS_DEPTH) {
if (value.getMom() != null) {
serializeParentData(gen, value.getMom(), currentDepth);
}
if (value.getDad() != null) {
serializeParentData(gen, value.getDad(), currentDepth);
}
}
}
private void serializeParentData(JsonGenerator gen, Foo value, int currentDepth) {
gen.writeObjectFieldStart(Gender.M.equals(value.getGender()) ? "dad" : "mom");
// other parameters ...
serializeParents(gen, value, currentDepth + 1);
gen.writeEndObject();
}