'Recursive JSON response in Postman of an entity with OneToMany relationship

I have a Client class which contains a list of Cars in a OneToMany relationship. When I try to GET all clients using Postman, the first client will be printed in the response recursively. How can i get the JSON response with the Client and its corresponding car list, without getting the client from the Car response too?

The Car class

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String model;
private String color;

@ManyToOne(fetch = FetchType.LAZY)
private Client client;

The Client class

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;

private int age;

@OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "client")
private List<Car> carList;

Image with the response in Postman

Image with the response in Postman



Solution 1:[1]

Assume you use Jackson to serialise to JSON , you can use @JsonIgnoreProperties to break the cycles:

Car:

@Entity
@Table(name= "Car")
public class Car {

    [.....]
    @JsonIgnoreProperties("carList")
    private Client client;
    [...]
}   

Client:

@Entity
@Table(name="client")
public class Client {

    [....]
    @JsonIgnoreProperties("client")
    private List<Car> carList;
    [...]
}

Solution 2:[2]

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String model;
private String color;
// Add this annotation
@JSONIgnoreProperties("carList")
@ManyToOne(fetch = FetchType.LAZY)
private Client client;



@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;

private int age;

__________________________________________________________________________

// add this annotation also here 
@JSONIgnoreProperties("client")
@OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "client")
private List<Car> carList;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ken Chan
Solution 2 Hitesh Kumar Sharma