1

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": {}
        }
    ]
3
  • check sub Objects and Arrays with !=null and .isEmpty() and !=0 and ""(string null). Commented Feb 24, 2022 at 4:56
  • will it work for json array like 'Caregiver' is this case, where all the child objects are empty Commented Feb 24, 2022 at 4:59
  • check jsonArray like this jsonArray.length()!=0 Commented Feb 24, 2022 at 5:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.