2011-08-20 11 views
2

Java에서 두 JSON 문자열을 비교하는 가장 좋은 방법은 무엇입니까? 키/값 쌍의 차이 만 인쇄 할 수 있기를 원합니다.두 개의 JSON 비교

나는지도로 변환하고 주장 할 라이브러리를 GSON 사용하고 있지만 모두 JSONs 표시

Type type = new TypeToken<Map<String, String>>() {}.getType(); 
Gson gson = new Gson(); 
Map<String, String> mapExpected = gson.fromJson(expectedJson, type); 
Map<String, String> mapResponse = gson.fromJson(jsonResponse, type); 
Assert.assertEquals(mapExpected, mapResponse); 

이 작업을 수행 할 수있는 더 나은 방법이 있나요를?

+0

을 계산 [설정 차이] [1]. [1] http://stackoverflow.com/questions/1723168/what-is-the-fastest-or-most-elegant-way-to-compute-a-set-difference-using-javascr/1723220#1723220 – mcandre

+0

@mcandre, 귀하의 링크는 JS에 관한 것입니다, 그는 Java에서 묻습니다 – SJuan76

+0

개념은 여전히 ​​적용 가능합니다 .JSON 데이터를 세트로 변환 한 다음 차이점 ('-')을 표시하십시오. – mcandre

답변

2

까다 롭지 만 할 수 있습니다.

String (키와 값)과 해당 equals() 및 hashcode()를 모두 포함하는 Pair 클래스를 구현했습니다.

그때 그런 result에서

Set<Pair> setA_B = setA.removeAll(setB); 
Set<Pair> setB_A = setB.removeAll(setA); 
Set<Pair> result = setA_B.addAll(setB_A); 

을 계산 모든 요소들이 집합 쌍으로하는 (setA)과 또 다른 세트 (setB)

지도 B 모든 요소를지도 넣어 일치하지 않는 요소 만 있습니다. 모든 요소가 일치하면 (원래지도가 모두 동일 함) result이 비어 있습니다.

+0

포인터에 대해 감사합니다 .SJuan76. 작품에서, 나는 AbstractMap의 SimpleEntry for Pair를 사용했다. – ypa

2

SJuan76의 솔루션을 사용하여 키 값 쌍의 차이를 얻을 수있었습니다.

Type type = new TypeToken<Map<String, String>>() {}.getType(); 
    Gson gson = new Gson(); 
    Map<String, String> mapExpected = gson.fromJson(expectedJson, type); 
    Map<String, String> mapResponse = gson.fromJson(jsonResponse, type); 
    Set<SimpleEntry<String,String>> expectedSet = new HashSet<SimpleEntry<String, String>>(); 
    Set<SimpleEntry<String, String>> tmpExpectedSet = new HashSet<SimpleEntry<String, String>>(); 
    Set<SimpleEntry<String, String>> responseSet = new HashSet<SimpleEntry<String, String>>(); 

    for (String key : mapExpected.keySet()) { 
     expectedSet.add(new SimpleEntry<String, String>(key, mapExpected.get(key))); 
     tmpExpectedSet.add(new SimpleEntry<String, String>(key, mapExpected.get(key))); 
    } 

    for (String key : mapResponse.keySet()) 
     responseSet.add((new SimpleEntry<String, String>(key, mapResponse.get(key)))); 

    expectedSet.removeAll(responseSet); 
    responseSet.removeAll(tmpExpectedSet); 
    expectedSet.addAll(responseSet); 

    if (!expectedSet.isEmpty()) { 
     for (SimpleEntry<String, String> diff : expectedSet) 
      log.error(diff.getKey() + ":" + diff.getValue()); 
    } 
3

단순한 동일성을 비교하기 만하면 Jackson을 사용하면 편리합니다. 그리고 이것이 도움이 될 수도 있습니다.

JsonNode tree1 = objectMapper.readTree(json1); 
JsonNode tree2 = objectMapper.readTree(json2); 
if (!tree1.equals(tree2)) { // handle diffing 
} 

Now; 모든 JsonNode 객체가 등호 검사를 올바르게 구현하므로 (키의 순서가 중요하지 않은 등) 재귀 적 diffing에 사용하여 내용이 다른 위치와 방법을 확인합니다. ObjectNode의 위해 당신은() 같은 (tree1.getFieldNames을 제거, 키 이름을 얻을 수 있습니다.에서 removeAll (등등 tree2.getFieldNames())와.