柚子快報激活碼778899分享:比較兩個JSON的不同
柚子快報激活碼778899分享:比較兩個JSON的不同
本例子使用Jackson庫來解析JSON字符串,并逐個比較JSON節(jié)點,包括對象、數(shù)組和值的差異。
主要功能包括:
ObjectMapper對象,用于將JSON字符串轉(zhuǎn)換為JsonNode對象。 compareJson 方法接受兩個JSON字符串,并將它們轉(zhuǎn)換為JsonNode對象,然后調(diào)用 compareNodes 方法來逐個比較節(jié)點。 compareNodes 方法是遞歸的,它會處理對象、數(shù)組和值的差異。如果兩個節(jié)點相同,它會直接返回。如果節(jié)點是對象,它會比較它們的字段,如果一個字段在一個JSON中有而在另一個中沒有,它會報告缺失字段。如果節(jié)點是數(shù)組,它會比較它們的元素,如果數(shù)組長度不同,它會報告長度不同。如果節(jié)點是值,它會比較它們的內(nèi)容,如果不同,它會報告值不同。
compareNodes 方法用于測試兩個JSON字符串是否相同,以及它們之間的差異。
示例代碼:
@Test
void text() {
String json1 = "{\"name\": \"小明\", \"age\": 30}";
String json2 = "{\"name\": \"大紅\", \"age\": 30}";
try {
compareJson(json1, json2);
} catch (IOException e) {
e.printStackTrace();
}
}
public void compareJson(String json1, String json2) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode tree1 = objectMapper.readTree(json1);
JsonNode tree2 = objectMapper.readTree(json2);
compareNodes(tree1, tree2);
}
private void compareNodes(JsonNode node1, JsonNode node2) {
if (node1.equals(node2)) {
return;
}
if (node1.isObject() && node2.isObject()) {
node1.fieldNames().forEachRemaining(fieldName -> {
if (!node2.has(fieldName)) {
System.out.println("字符串 '" + fieldName + "' 在第二個JSON中丟失.");
} else {
JsonNode childNode1 = node1.get(fieldName);
JsonNode childNode2 = node2.get(fieldName);
compareNodes(childNode1, childNode2);
}
});
node2.fieldNames().forEachRemaining(fieldName -> {
if (!node1.has(fieldName)) {
System.out.println("字符串 '" + fieldName + "' 在第二個JSON中丟失.");
}
});
} else if (node1.isArray() && node2.isArray()) {
int size1 = node1.size();
int size2 = node2.size();
if (size1 != size2) {
System.out.println("數(shù)組大小不匹配: " + size1 + " 在第一個JSON中 and " + size2 + " 在第二個JSON中.");
}
int minSize = Math.min(size1, size2);
for (int i = 0; i < minSize; i++) {
compareNodes(node1.get(i), node2.get(i));
}
} else {
System.out.println("值不匹配: " + node1 + " 在第一個JSON中 and " + node2 + " 在第二個JSON中.");
}
}
柚子快報激活碼778899分享:比較兩個JSON的不同
相關(guān)文章
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。