Issue
I write a API Restful services. But JSON has to change now. I have to remove some fields in output JSON in output.
my JSON is:
{
"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
},
]
},
But, the requirement is something like this:
{
"id": "10001",
"name": "math",
"family": "mac",
"code": "1",
"subNotes": [
{
"name": "john",
"code": "1-1",
},
{
"name": "cris",
"code": "1-2",
},
{
"name": "eli",
"code": "1-3",
},
]
},
can I change it without create 2 Object (parent, child) ? what's better solution ?
Solution
You can ignore null fields at the class level by using @JsonInclude(Include.NON_NULL)
to only include non-null fields, thus excluding any attribute whose value is null.
@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;
}
and then my result:
{
"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
Answered By - hungtv
Answer Checked By - Timothy Miller (JavaFixing Admin)