这条规则
{"==" : [ { "var" : "code" }, "ER"]}
使用此数据给出正确答案(true)
{"code": "ER", "name": "Exploratory Research"}
使用 javascript 游乐场。
但是,这段Java代码
JavaJsonLogic jsonLogic = JavaJsonLogic.INSTANCE;
String rule = "{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]}";
JsonObject data = new JsonObject();
data.addProperty("code", "ER");
data.addProperty("name", "Exploratory Research")
System.out.println(jsonLogic.apply(rule, data)););
回归
false
!
JsonLogic jsonLogic = new JsonLogic();
String rule = "{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]}";
//JsonObject data = new JsonObject();
Map<String, Object> data = new HashMap<>();
data.put("name", "Exploratory Research");
data.put("code", "ER");
jsonLogic.apply(rule, data);
我正在使用哈希图来填充值来代替
JsonObject
。结果证明是正确的。我还使用 https://mvnrepository.com/artifact/io.github.jamsesso
来解析 jsonLogic 字符串并通过 jsonlogic 验证数据。
万一有人遇到这个问题,迟到总比不到好:)
我的代码也有同样的问题。我需要访问对象内部列表中对象的属性。
您必须将对象转换为地图,这对我有用,请参考此处https://www.baeldung.com/java-convert-object-to-map:
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper
.convertValue(employee, new TypeReference<Map<String, Object>>() {});
jsonLogic.apply(rule, map);
dmillerw 也根据您遵循的 jsonlogic 规范为 java 实现了 jsonlogic 实现。我只是尝试从下面的 URL 中获取代码库并使用您的测试数据,它的工作就像一个魅力。
https://github.com/dmillerw/json-logic-java
这是我在我的单位中用来测试您的需求的内容:
String testjson = **"[[{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]},{\"code\": \"ER\", \"name\": \"Exploratory Research\"},true]]";**
JsonArray testArray = gson.fromJson(testjson, JsonArray.class);
for (JsonElement element : testArray) {
JsonArray array = element.getAsJsonArray();
JsonElement test = array.get(0);
JsonElement data = array.get(1);
JsonElement expected = array.get(2);
System.out.println(**JsonLogic.apply(test, data)**);
}