如何编写JSONCustomComparator (不是针对特定字段,而是针对特定数据类型)?
我知道一个特定的领域,我能做到,
CustomComparator comparator = new CustomComparator(
JSONCompareMode.LENIENT,
new Customization("field.nunber", (o1, o2) -> true),
new Customization("field.code", (o1, o2) -> true));
JSONAssert.assertEquals(expectedJsonAsString, actualJsonAsString, comparator);但是,如何对特定的数据类型执行此操作呢?例如,我必须比较布尔和Int(真与1,假与0),
ValueMatcher<Object> BOOL_MATCHER = new ValueMatcher<Object>() {
@Override
public boolean equal(Object o1, Object o2) {
if (o1.toString().equals("true") && o2.toString().equals("1")) {
return true;
} else if (o1.toString().equals("false") && o2.toString().equals("0")) {
return true;
} else if (o2.toString().equals("true") && o1.toString().equals("1")) {
return true;
} else if (o2.toString().equals("false") && o1.toString().equals("0")) {
return true;
}
return JSONCompare.compareJSON(o1.toString(), o2.toString(), JSONCompareMode.LENIENT).passed();
}
};
CustomComparator comparator = new CustomComparator(JSONCompareMode.LENIENT, new Customization("*", BOOL_COMPARATOR));但是--这似乎不是最好的方法,而且BOOL_MATCHER只返回布尔值,而不是JSONCompareResult,这样就可以显示diff。
有更好的方法吗?
发布于 2022-11-25 09:26:56
通过扩展DefaultComparator创建一个新的自定义比较器。
private static class BooleanCustomComparator extends DefaultComparator {
public BooleanCustomComparator(final JSONCompareMode mode) {
super(mode);
}
@Override
public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result)
throws JSONException {
if (expectedValue instanceof Number && actualValue instanceof Boolean) {
if (BooleanUtils.toInteger((boolean)actualValue) != ((Number) expectedValue).intValue()) {
result.fail(prefix, expectedValue, actualValue);
}
} else if (expectedValue instanceof Boolean && actualValue instanceof Number) {
if (BooleanUtils.toInteger((boolean)expectedValue) != ((Number) actualValue).intValue()) {
result.fail(prefix, expectedValue, actualValue);
}
} else {
super.compareValues(prefix, expectedValue, actualValue, result);
}
}
}用法:
JSONAssert.assertEquals(expectedJson, actualJson, new BooleanCustomComparator(JSONCompareMode.STRICT));https://stackoverflow.com/questions/74569761
复制相似问题