1 year ago
#219067
Amit
JsonNode remove empty nodes
I have a Dynamic JsonNode without POJO like this:
{
"Patient": {
"Addresses": {},
"Phones": {},
"Faxes": {},
"FirstName": "Test",
"LastName": "Test",
"DateOfBirth": "5/5/1945 12:00:00 AM",
"Allergies": {},
"AdditionalInformation": {}
},
"Caregiver": [
{
"Addresses": {},
"Phones": {},
"Faxes": {},
"AdditionalInformation": {}
}
],
"Physician": [
{
"Addresses": {},
"Phones": {},
"Faxes": {},
"ContactPhone": {},
"ContactFax": {},
"Facility": {
"Addresses": {},
"Phones": {},
"Faxes": {},
"ContactPhone": {},
"ContactFax": {}
},
"AdditionalInformation": {}
}
]
}
I need to remove empty objects '{}' from the JSON, such that the response looks like this:
{
"Patient": {
"FirstName": "Test",
"LastName": "Test",
"DateOfBirth": "5/5/1945 12:00:00 AM",
},
"Caregiver": [],
"Physician": []
}
If all the objects within JSON arrays are empty, then need to remove them.
I tried with ObjectMapper from Jackson, but no luck.
public static JsonNode stripEmpty(JsonNode node) {
Iterator<JsonNode> it = node.iterator();
while (it.hasNext()) {
JsonNode child = it.next();
if (child.isObject() && child.isEmpty(null))
it.remove();
else
stripEmpty(child);
}
return node;
}
I tried above code and it returned as:
"Patient": {
"FirstName": "Test",
"LastName": "Test",
"DateOfBirth": "5/5/1945 12:00:00 AM"
},
"Caregiver": [
{}
],
"Physician": [
{
"Facility": {}
}
]
java
arrays
json
jsonnode
0 Answers
Your Answer