1

我有一个没有 POJO 的动态 JsonNode,如下所示:

{
"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": {}
        }
    ]
}

我需要从 JSON 中删除空对象“{}”,以便响应如下所示:

{
"Patient": {
        "FirstName": "Test",
        "LastName": "Test",
        "DateOfBirth": "5/5/1945 12:00:00 AM",
    },
    "Caregiver": [],
    "Physician": []
}

如果 JSON 数组中的所有对象都是空的,则需要删除它们。

我尝试使用 Jackson 的 ObjectMapper,但没有运气。

 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;
    }

我尝试了上面的代码,它返回为:

 "Patient": {
        "FirstName": "Test",
        "LastName": "Test",
        "DateOfBirth": "5/5/1945 12:00:00 AM"
    },
    "Caregiver": [
        {}
    ],
    "Physician": [
        {
            "Facility": {}
        }
    ]
4

0 回答 0