简体   繁体   中英

List<object> null when deserializing json in Spring Boot controller

I have a problem with a controller in a Spring Boot application. When I make a call on the controller (URI/call), the object list is always null.

{
    "code": "TEST",
    "name": "TEST NAME",
    "groupe": "A1",
    "list": [
        {"type":"web", "link":"https://google.com/"},
        {"type":"web", "link":"https://google2.com/"}
    ]
}
@PostMapping(value="/call")
    public ResponseEntity<Void> ajouterEnvironnement(@RequestBody First first) {
        first.getCode() // value : "TEST"
        first.getList() // value : null
}
public class First {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String code;
    private String name;
    private String groupe;
    @OneToMany(mappedBy = "first", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Second> list;
}
public class Second {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String type;
    private String link;
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "first_id", nullable = false)
    private First first;
}

By writing this question, I was able to find a solution, so I share it:

Use the @JsonManagedReference and @JsonBackReference annotations.

More information here .

public class First {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String code;
    private String name;
    private String groupe;
    @OneToMany(mappedBy = "first", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JsonManagedReference
    private List<Second> listLiens;
}
public class Second {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String type;
    private String link;
    @ManyToOne(fetch = FetchType.EAGER)
    @JsonBackReference
    @JoinColumn(name = "first_id", nullable = false)
    private First first;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM