[英]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.