[英]how to generate dynamic Json in Spring boot
我寫了一個 API Restful 服務。 但是 JSON 現在必須改變。 我必須刪除 output 中 output JSON 中的一些字段。
我的 JSON 是:
{
"id": "10001",
"name": "math",
"family": "mac",
"code": "1",
"subNotes": [
{
"id": null,
"name": "john",
"family": null,
"code": "1-1",
"subNotes": null
},
{
"id": null,
"name": "cris",
"family": null,
"code": "1-2",
"subNotes": null
},
{
"id": null,
"name": "eli",
"family": null,
"code": "1-3",
"subNotes": null
},
]
},
但是,要求是這樣的:
{
"id": "10001",
"name": "math",
"family": "mac",
"code": "1",
"subNotes": [
{
"name": "john",
"code": "1-1",
},
{
"name": "cris",
"code": "1-2",
},
{
"name": "eli",
"code": "1-3",
},
]
},
我可以在不創建 2 Object(父、子)的情況下更改它嗎? 有什么更好的解決方案?
您可以使用@JsonInclude(Include.NON_NULL)
忽略 class 級別的 null 字段以僅包含非空字段,從而排除值為 Z37A6259CC0C1DAE299A7866489DFF0BD 的任何屬性。
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class testDto {
private String id;
private String name;
private String family;
private String code;
private List<testDto> subNotes;
}
然后是我的結果:
{
"id": "10001",
"name": "math",
"family": "mac",
"code": "1",
"subNotes": [
{
"name": "john",
"code": "1-1"
},
{
"name": "cris",
"code": "1-2"
}
]
}
Documentation: 3 ways to ignore null fields while converting Java object to JSON using Jackson
我使用了 jackson 注釋,它工作正常。
import com.fasterxml.jackson.annotation.JsonInclude.Include;
public class TestDto implements Serializable {
@JsonInclude(Include.NON_NULL)
private String id;
@JsonInclude(Include.NON_NULL)
private String name;
@JsonInclude(Include.NON_NULL)
private String family;
@JsonInclude(Include.NON_NULL)
private String code;
@JsonInclude(Include.NON_NULL)
private List<TestDto> subNotes;
//getter and setter ...
}
有 3 種方法可以重構相同的 Object 而無需為您的目的創建另一個
第 2、3 點已在答案中共享,因此對於第一個選項
public class testDto {
@JsonIgnore
private String id;
private String name;
@JsonIgnore
private String family;
private String code;
@JsonIgnore
private List<testDto> subNotes;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.