如何使用skyscreamer (JSONAssert)为特定数据类型编写json自定义比较器? &g



如何为特定的数据类型而不是特定的字段编写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值(true为1,false为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可以显示。

有更好的方法吗?

通过扩展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));

最新更新