我有一个 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”比较。
我该如何实现。
最佳答案
创建自定义 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);
根据我们在评论中的讨论,这里有一个使用 Guava 库比较任意两个 JSON 对象同时过滤掉任意一组键的通用解决方案:
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);
}
关于java - 如何在json比较中跳过一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38707608/