Kalyan Pradhan Kalyan Pradhan - 6 months ago 37
JSON Question

How to handle infinite recursion of Jackson

My problem is I have two classes as follows

public class User implements UserDetails {
@Id
@GeneratedValue
@Column(name = "user_id")
private Long Id;
@OneToOne
@JsonManagedReference
private Wallet wallet;
.........
// Getters and setters..
}


And

@Entity
public class Wallet {

@Id
@GeneratedValue
private Long Id;
@OneToOne()
@JsonBackReference
private User user;
.........
//Getters and setters.
}


Sometimes I need the
Wallet
information from the
User
model and at other times I need the reverse.

So, if I write Json Ignore or Json back reference on any of the side I cant get the other object.

For example : If I write
@JsonBackReference
in
Wallet
class I cant get the
User
Information while querying the
Wallet
.

My question is how to handle this situation. I have tried both
@JsonIgnore
and
@JsonBackReference


Thanks in advance.

Answer

If you are using Jackson 2.0+, you may use @JsonIdentityInfo to solve your issue.

Here are the docs with a complete example.

Comments