Java实现忽略属性顺序与JSON数组元素顺序的响应对比
Java实现JSON响应对比(忽略属性顺序、忽略数组元素顺序)
实现两个JSON对比,满足核心规则:
- 忽略JSON对象属性的排序,按键名匹配对比
- 忽略JSON数组内部元素的排序,默认按数组元素的
id属性匹配对应元素对比 - 最终输出结构化的差异列表
依赖引入
使用Jackson处理JSON,Maven依赖如下:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>
定义差异实体类
用来存储每一条差异记录,没有Lombok可自行编写getter、setter、全参构造方法:
import lombok.Data; @Data public class Difference { private String result; private String targetPath; private String sourcePath; private Object targetValue; private Object sourceValue; public Difference(String result, String targetPath, String sourcePath, Object targetValue, Object sourceValue) { this.result = result; this.targetPath = targetPath; this.sourcePath = sourcePath; this.targetValue = targetValue; this.sourceValue = sourceValue; } }
核心对比工具类实现
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ValueNode; import java.util.*; public class JsonCompareUtil { private static final ObjectMapper objectMapper = new ObjectMapper(); // 数组元素匹配的唯一键,可根据业务需求修改 private static final String ARRAY_MATCH_KEY = "id"; public static List<Difference> compare(String targetJson, String sourceJson) throws Exception { JsonNode targetNode = objectMapper.readTree(targetJson); JsonNode sourceNode = objectMapper.readTree(sourceJson); List<Difference> differences = new ArrayList<>(); compareNode(targetNode, sourceNode, "", "", differences); return differences; } private static void compareNode(JsonNode targetNode, JsonNode sourceNode, String targetPath, String sourcePath, List<Difference> differences) { // 两个节点都为空无差异 if (targetNode == null && sourceNode == null) { return; } // 目标节点存在、源节点缺失 if (targetNode != null && sourceNode == null) { differences.add(new Difference("attribute not found in source response", targetPath, null, getNodeValue(targetNode), null)); return; } // 源节点存在、目标节点缺失 if (targetNode == null) { differences.add(new Difference("attribute not found in target response", null, sourcePath, null, getNodeValue(sourceNode))); return; } // 节点类型不匹配 if (targetNode.getNodeType() != sourceNode.getNodeType()) { differences.add(new Difference("mismatch", targetPath, sourcePath, getNodeValue(targetNode), getNodeValue(sourceNode))); return; } switch (targetNode.getNodeType()) { case OBJECT: // 遍历目标所有属性对比 Iterator<String> targetFields = targetNode.fieldNames(); while (targetFields.hasNext()) { String field = targetFields.next(); String newTargetPath = targetPath + "." + field; String newSourcePath = sourcePath + "." + field; compareNode(targetNode.get(field), sourceNode.get(field), newTargetPath, newSourcePath, differences); } // 检查源独有的属性 Iterator<String> sourceFields = sourceNode.fieldNames(); while (sourceFields.hasNext()) { String field = sourceFields.next(); if (!targetNode.has(field)) { String newSourcePath = sourcePath + "." + field; differences.add(new Difference("attribute not found in target response", null, newSourcePath, null, getNodeValue(sourceNode.get(field)))); } } break; case ARRAY: // 数组按唯一匹配键转成Map,忽略顺序匹配元素 Map<Object, JsonNode> targetMap = buildArrayMap(targetNode); Map<Object, JsonNode> sourceMap = buildArrayMap(sourceNode); // 遍历目标数组元素对比 for (Map.Entry<Object, JsonNode> entry : targetMap.entrySet()) { Object key = entry.getKey(); String newTargetPath = targetPath + "[id=" + key + "]"; String newSourcePath = sourcePath + "[id=" + key + "]"; compareNode(entry.getValue(), sourceMap.get(key), newTargetPath, newSourcePath, differences); } // 检查源数组独有的元素 for (Map.Entry<Object, JsonNode> entry : sourceMap.entrySet()) { Object key = entry.getKey(); if (!targetMap.containsKey(key)) { String newSourcePath = sourcePath + "[id=" + key + "]"; differences.add(new Difference("array element not found in target response", null, newSourcePath, null, getNodeValue(entry.getValue()))); } } break; // 值类型直接对比内容 case STRING: case NUMBER: case BOOLEAN: case NULL: if (!targetNode.equals(sourceNode)) { differences.add(new Difference("mismatch", targetPath, sourcePath, getNodeValue(targetNode), getNodeValue(sourceNode))); } break; default: break; } } private static Map<Object, JsonNode> buildArrayMap(JsonNode arrayNode) { Map<Object, JsonNode> map = new HashMap<>(); for (int i = 0; i < arrayNode.size(); i++) { JsonNode element = arrayNode.get(i); if (element.has(ARRAY_MATCH_KEY)) { Object key = getNodeValue(element.get(ARRAY_MATCH_KEY)); map.put(key, element); } else { // 无匹配键时按元素哈希值匹配,可根据需求调整逻辑 map.put(element.hashCode(), element); } } return map; } private static Object getNodeValue(JsonNode node) { if (node == null) return null; if (node.isValueNode()) { ValueNode valueNode = (ValueNode) node; if (valueNode.isTextual()) return valueNode.asText(); if (valueNode.isInt()) return valueNode.asInt(); if (valueNode.isLong()) return valueNode.asLong(); if (valueNode.isBoolean()) return valueNode.asBoolean(); if (valueNode.isNull()) return null; } return node.toString(); } }
使用示例
public class CompareTest { public static void main(String[] args) throws Exception { // 需补全引号符合标准JSON格式 String targetJson = "{\n" + " \"name\":\"abc\",\n" + " \"category\":\"bbb\",\n" + " \"place\":\"aaa\",\n" + " \"arrayList\":[\n" + " {\n" + " \"id\":1,\n" + " \"description\":\"blah blah\",\n" + " \"count\":3\n" + " },\n" + " {\n" + " \"id\":2,\n" + " \"count\":4,\n" + " \"description\":\"blah blah\"\n" + " }\n" + " ]\n" + "}"; String sourceJson = "{\n" + " \"name\":\"abc\",\n" + " \"place\":\"aaa\",\n" + " \"category\":\"ccc\",\n" + " \"arrayList\":[\n" + " {\n" + " \"id\":2,\n" + " \"description\":\"blah blah\",\n" + " \"count\":3\n" + " },\n" + " {\n" + " \"id\":1,\n" + " \"count\":3\n" + " }\n" + " ]\n" + "}"; List<Difference> differences = JsonCompareUtil.compare(targetJson, sourceJson); differences.forEach(diff -> { try { System.out.println(new ObjectMapper().writeValueAsString(diff)); } catch (Exception e) { e.printStackTrace(); } }); } }
运行后输出的差异列表和预期一致,包含三条差异:category值不匹配、id为1的元素缺失description属性、id为2的元素count值不匹配。
内容的提问来源于stack exchange,提问作者SasukeUchiha
相关产品推荐
相关产品推荐

