java – I have a Json List and XML list, Have to remove the Fields in JSon which are null and not present in the xml list and store it in new list

parsedJsonChildData (original data): [{date=null, feeForPerformance=null, feeFrequency=5}, {date=12-25-2024, feeForPerformance=23, feeFrequency=1}, {date=12-03-2025, feeForPerformance=1, feeFrequency=5}]

parsedXmlChildData (original data): [{date=null, feeFrequency=5}, {date=12-25-2024, feeForPerformance=23, feeFrequency=1}, {date=12-03-2025, feeForPerformance=1, feeFrequency=5}]

In the first index of parsedJsonChildData feeForPerformance=null should be remove since it is not available in the parsedXmlChildData

I have tried to make a code but I am still getting the same output

public static List> cleanJsonData(List> parsedJsonChildData, List> parsedXmlChildData) {
    List> modifiedParsedJsonChildData = new ArrayList<>();

    // Iterate over each index in the JSON and XML lists
    for (int i = 0; i < parsedJsonChildData.size(); i++) {
        Map jsonObject = parsedJsonChildData.get(i);
        Map xmlObject = parsedXmlChildData.get(i);

        // Create a new map to hold the cleaned JSON object
        Map cleanedJsonObject = new HashMap<>(jsonObject);

        // Iterate over the entries in the JSON object
        Iterator> iterator = cleanedJsonObject.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            String jsonField = entry.getKey();
            Object jsonValue = entry.getValue();

            // If the field is null in JSON and is missing in XML, remove it from JSON
            if (jsonValue == null && !xmlObject.containsKey(jsonField)) {
                iterator.remove(); // Remove the field from the copied JSON
                System.out.println("Removed field from JSON: " + jsonField); // Log the removal
            }
        }

        // Add the cleaned JSON object to the modified list
        modifiedParsedJsonChildData.add(cleanedJsonObject);
    }

    return modifiedParsedJsonChildData; // Return the cleaned JSON data only
}

ouptut :-

modifiedParsedJsonChildData (after cleaning): [{date=null, feeForPerformance=null, feeFrequency=5}, {date=12-25-2024, feeForPerformance=23, feeFrequency=1}, {date=12-03-2025, feeForPerformance=1, feeFrequency=5}]

it is still the same

Read more here: Source link