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}]
在
parsedJsonChildData
的第一个索引中,应删除 feeForPerformance=null
,因为它在 parsedXmlChildData
中不可用,标准是如果该字段在 parsedJsonChildData 中为 Null 并且不存在于 parsedXmlChildData 中,则应从 parsedJsonChildData 中删除它
我尝试编写代码,但仍然得到相同的输出
public static List<Map<String, Object>> cleanJsonData(List<Map<String, Object>> parsedJsonChildData, List<Map<String, Object>> parsedXmlChildData) {
List<Map<String, Object>> modifiedParsedJsonChildData = new ArrayList<>();
// Iterate over each index in the JSON and XML lists
for (int i = 0; i < parsedJsonChildData.size(); i++) {
Map<String, Object> jsonObject = parsedJsonChildData.get(i);
Map<String, Object> xmlObject = parsedXmlChildData.get(i);
// Create a new map to hold the cleaned JSON object
Map<String, Object> cleanedJsonObject = new HashMap<>(jsonObject);
// Iterate over the entries in the JSON object
Iterator<Map.Entry<String, Object>> iterator = cleanedJsonObject.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> 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
}
输出:
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}]
还是一样
我找到了一个可行的解决方案
公共静态列表
for (int i = 0; i < parsedJsonChildData.size(); i++) {
Map<String, Object> jsonItem = parsedJsonChildData.get(i);
Map<String, Object> xmlItem = parsedXmlChildData.get(i);
Map<String, Object> filteredItem = new HashMap<>();
for (Map.Entry<String, Object> entry : jsonItem.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if ((value != null && !value.toString().isEmpty()) || xmlItem.containsKey(key)) {
filteredItem.put(key, value);
}
}
modifiedParsedJsonChildData.add(filteredItem);
}
return modifiedParsedJsonChildData;
}