Search code examples
javaspringspring-mvcjacksonspring-web

Modify object serialization depending on what class is being serialized


So my goal is to return some objects as the response body from a Spring REST controller. The thing is, these two objects point each other, something kind of like this:

public class Person {
    private Set<Team> teams;
}

public class Team {
    private Set<Person> members;
}

If I return these two objects from a controllers mapping method right away, the generated response will be infinite and will probably crash the browser, because the members set has people, and each person has a set of teams, and so on, and everything gets returned infinitely.

How can I manage, instead of showing the whole list of, say, members, to display just the name of each of the members?

Any help will be much appreciated, thanks!


Solution

  • If you are using jackson then you must use jackson provided solution to problem you are mentioning.

    1. @JsonManagedReference
    2. @JsonBackReference

    Also look at this link which might be helpful : Infinite Recursion with Jackson JSON and Hibernate JPA issue,

    Also https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations#object-references-identity