package com.seeyon.apps.esign.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.util.Iterator;
import java.util.Map;

public class JsonCleaner {

    public static String removeEmptyObjects(String jsonStr) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode node = (ObjectNode) mapper.readTree(jsonStr);

        Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
        while (fields.hasNext()) {
            Map.Entry<String, com.fasterxml.jackson.databind.JsonNode> entry = fields.next();
            if (entry.getValue().isObject() && entry.getValue().isEmpty()) {
                fields.remove();
            }
        }

        return mapper.writeValueAsString(node);
    }


}