Spring Boot(使用Jackson)可以很好地處理JSON文檔和Java POJO之間的對象映射。例如:Spring Boot中發佈的JSON中的實體關係
{ id: 5, name: "Christopher" }
可以被接受:
@PostMapping("/students/{id}")
public Student Update(Long studentId, @RequestBody Student student) {
studentRepository.save(student);
return student;
}
,將正確地映射到:在JSON
public class Student {
private Long id;
private String name;
...
}
但對於嵌套的模式?
{ id: 5, name: "Christopher", grades: [ {id: 1, letter: 'A'} ] }
或者JSON中的可選模型?
{ id: 5, name: "Christopher" }
(Purposefully leaving out 'grades', though it could be accepted.)
或者表明刪除了JSON中的關聯(例如使用Rails的_destroy標誌)?
{ id: 5, name: "Christopher", grades: [ {id: 1, letter: 'A', _destroy: true} ] }
或者通過忽略ID來創建關聯?
{ id: 5, name: "Christopher", grades: [ {letter: 'A-'} ] }
Spring Boot是否支持這些想法?
如果您的意思是'可選模型',可選,你不應該在Pojos中使用Optionals。 –
不一定是可選模型,只是可選的,不管它是否應該在JSON中。如果'學生'有一份'成績'列表,但我只想更新一個學生的姓名,我不希望每次都發布他們的'成績'數組。 – Christopher
我使用數據傳輸對象(DTO)來解決您描述的問題。您還可以在不想序列化的字段上添加@JsonIgnore註釋。 –