我有兩個 endPoints 回傳這個 Json :
"type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}
我需要讓它忽略第一個端點的 desc 并讓它第二個,除了創建另一個 ResponseDTO 之外還有什么解決方案嗎?
@jsonIgnore將忽略所有端點的屬性。
對于第一個端點:無 desc
"type": {
"nbrCurrentRemainingDays": 0,
"id": 32
}
第二個:帶 desc
"type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}
uj5u.com熱心網友回復:
@JsonInclude(Include.NON_EMPTY)應該做的伎倆。
Include.NON_EMPTY:表示只有非空的屬性才會包含在 JSON 中。
最簡單的解決方案,
根.java
public class Root {
public Type type;
//Todo getter setter constructor
}
型別.java
public class Type {
public int nbrCurrentRemainingDays;
@JsonInclude(Include.NON_EMPTY)
public String desc;
public int id;
//Todo getter setter constructor
}
MyController.java
@RestController
public class MyController {
@GetMapping("/all-fields")
public Root test1() {
Root root = new Root();
Type type = new Type();
type.setNbrCurrentRemainingDays(0);
type.setId(32);
type.setDesc("put desc here !");
root.setType(type);
return root;
}
@GetMapping("/ignore-desc")
public Root test2() {
Root root = new Root();
Type type = new Type();
type.setNbrCurrentRemainingDays(0);
type.setId(32);
type.setDesc("put desc here !");
root.setType(type);
//Set null value
type.setDesc(null);
return root;
}
}
端點 1:localhost:8080/all-fields(帶 desc)
{
"type": {
"nbrCurrentRemainingDays": 0,
"desc": "put desc here !",
"id": 32
}
}
端點 2: localhost:8080/ignore-desc(no desc)
{
"type": {
"nbrCurrentRemainingDays": 0,
"id": 32
}
}
uj5u.com熱心網友回復:
對欄位使用@JsonIgnore 注釋,并為desc 欄位創建手動getter 和setter,其中setter 將根據欄位值回傳。
setter、Getter方法需要用@JsonProperty注解,現在setter會根據URL路徑(或者根據你選擇的任何條件)回傳值。
uj5u.com熱心網友回復:
我知道一個解決方案。您可以擴展 Json Serializer 類并覆寫其中的序列化方法。您可以禁用不需要的欄位。像這樣
JsonView
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/459166.html
