2016-08-01 39 views
0

一個節點我有一個JSON比較如何跳過JSON對比

class JSONUtils { 

public static void areEqual(def context_1, def context_2) { 
    Object obj1,obj2; 
    Object json = new JSONTokener(context_1).nextValue(); 
    if (json instanceof JSONObject) { 
     obj1 = new JSONObject(context_1); 
     obj2 = new JSONObject(context_2); 
    } else if (json instanceof JSONArray) { 
     obj1 = new JSONArray(context_1); 
     obj2 = new JSONArray(context_2); 
    } 
    def ObjectMapper mapper = new ObjectMapper(); 
    def JsonNode tree1 = mapper.readTree(obj1.toString()); 
    def JsonNode tree2 = mapper.readTree(obj2.toString()); 
    assert tree1.equals(tree2); 
    } 
} 

當兩個JSON是完全一樣的正常工作。我有一個特殊情況,在比較時需要跳過或忽略兩個節點值。

實施例:

First Json: 
{ 
    "rd":12, 
    "td":"text1" 
    "dt": 123456, 
    "vt": "west" 
} 
Second Json: 
{ 
    "rd":12, 
    "td":"text1" 
    "dt": 333333, 
    "vt": "east" 
} 

我需要忽略或跳過 「DT」 和 「VT」 比較。

我該如何實現它。

回答

2

創建自定義POJO持有你所關心的值:

// Ignore fields "dt" and "vt" 
@JsonIgnoreProperties(ignoreUnknown = true) 
public class MyType { 
    // Ideally these should use getters/setters 
    public int rd; 
    public String td; 

    @Override 
    public boolean equals(Object obj) { 
     if (obj instanceof MyType) { 
      MyType t = (MyType)obj; 
      return t.rd == this.rd 
        && Objects.equals(t.td, this.td); 
     } 
     return false; 
    } 

    // hashCode() should always be overriden alongside equals() 
    @Override 
    public int hashCode() { 
     return Objects.hash(rd, td); 
    } 
} 

在你的代碼,你可以建造和他們這樣的比較:

ObjectMapper mapper = new ObjectMapper(); 
MyType t1 = mapper.readValue(obj1.toString(), MyType.class); 
MyType t2 = mapper.readValue(obj2.toString(), MyType.class); 
assert t1.equals(t2); 

根據我們的討論中評論,這裏有一個通用的解決方案來比較任何兩個JSON對象,同時使用Guava庫過濾掉任何密鑰集:

public static boolean jsonEquals(String json1, String json2, String... ignoreKeys) throws IOException { 
    // this is a Guava Predicate 
    Predicate<String> filter = Predicates.not(Predicates.in(Sets.newHashSet(ignoreKeys))); 

    ObjectMapper mapper = new ObjectMapper(); 
    Map<String, Object> object1 = Maps.filterKeys(mapper.readValue(json1, Map.class), filter); 
    Map<String, Object> object2 = Maps.filterKeys(mapper.readValue(json2, Map.class), filter); 
    return object1.equals(object2); 
} 
+0

com.fasterxml.jackson.databind.JsonMappingException:無法將[com.dynatrace.groovysupport.MyType的實例反序列化爲START_ARRAY令牌 at [Source:[{「id」:23,「type」:1}, { 「ID」:24, 「類型」:1}];行:1,柱:1] \t在com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) \t在 – ChanChow

+0

@AllIsWell'[{ 「ID」:23, 「類型」:1} ,{「id」:24,「type」:1}]'與您在問題中發佈的內容無關。 – shmosel

+0

我正在嘗試這個數據\t static def context_3 =「[{\」type \「:1,\」id \「:23},{\」type \「:1,\」id \「:24} ]「; \t static def context_4 =「[{\」type \「:1,\」id \「:23},{\」type \「:1,\」id \「:24}]」; – ChanChow