2016-09-29 38 views
2

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是否支持這些想法?

+0

如果您的意思是'可選模型',可選,你不應該在Pojos中使用Optionals。 –

+0

不一定是可選模型,只是可選的,不管它是否應該在JSON中。如果'學生'有一份'成績'列表,但我只想更新一個學生的姓名,我不希望每次都發布他們的'成績'數組。 – Christopher

+0

我使用數據傳輸對象(DTO)來解決您描述的問題。您還可以在不想序列化的字段上添加@JsonIgnore註釋。 –

回答

1

但是,JSON中的嵌套模型呢?

嵌套模型映射,你也許會想到,假設你有以下型號:

public class Product { 
    private String name; 
    private List<Price> prices; 
} 


public class ProductPrice { 
    Long idPrice; 
    Integer amountInCents; 
} 

傑克遜會從這個模式創建以下JSON:

{ 
    "name":"Samsung Galaxy S7", 
    "prices":[ 
     { 
       "idPrice":0, 
       "amountInCents": 100 
     } 
    ] 
} 

或者JSON中的可選模型?

您可以使用@JsonIgnore註釋字段。例如,如果您使用@JsonIgnore標註價格,則不會從傑克遜序列化價格。

或者表明刪除JSON中的關聯(例如使用 Rails的_destroy標誌)?

我會創建一個額外的映射來刪除關聯。這還有一個好處,這個API是自我解釋..

@DeleteMapping("/students/{id}/grade/{idGrade}") 
public Student Update(Long studentId, @PathVariable Long idGrade) { 

    studentService.deleteGrade(studentId,idGrade); 

    return student; 
} 

或創建留下了ID的關聯?

我會在這裏還可以創建一個額外的映射:

@PostMapping("/students/{id}/grade") 
public Student Update(Long studentId, @PathVariable String grade) { 

    studentService.addGrade(studentId,grade); 

    return student; 
} 

注:我不直接使用存儲庫,我創建了一個服務層,每個倉庫都有包裝保護訪問。在服務層中,您創建諸如addGrade,deleteGrad,addStudent,deleteStudent等方法

+0

謝謝,這是一個相當完整的答案。但是,如果我只想在包含數據的情況下序列化嵌套模型呢? @JsonIgnore的行爲好像該關聯根本不存在。但是我可能想同時用它的嵌套對象創建一個對象,或者我可能希望將其忽略掉。這種行爲是否被支持? – Christopher

+0

我從來沒有嘗試過,但看看傑克遜JSON Views。我認爲這應該適合你的目標。這裏有一篇不錯的博客文章:http://www.baeldung.com/jackson-json-view-annotation –

相關問題