jamsesso / json-logic-java

A pure Java implementation of JsonLogic without using the Nashorn JS engine
MIT License
99 stars 50 forks source link

How could this be equal #30

Closed 0019 closed 1 year ago

0019 commented 2 years ago

`import io.github.jamsesso.jsonlogic.JsonLogic; import io.github.jamsesso.jsonlogic.JsonLogicException;

public class RuleEngine {

private final static JsonLogic jsonLogic = new JsonLogic();

public static void main(String[] args) throws JsonLogicException {
    String expression = "{\"==\": [{\"var\": \"x.value\"}, {\"var\": \"y.value\"}]}";
    String data = "{\"x\": {\"value\": 0}, \"y\": {\"value\": 1}}";

    Boolean result = (Boolean)jsonLogic.apply(expression, data);
    if (result)
        System.out.println("equal");
}

} `

What did I miss? It's driving me crazy...

0019 commented 2 years ago

Well, if I specify the data in a map then it works:

Map d = new HashMap<String, Integer>(){{ put("x", 0); put("y", 1); }};

Does it only take in map? What if my data is nested?

grzegorz-taramina commented 1 year ago

I'm having exactly the same problem. The library doesn't seem to support nested objects. Any plans to enhance it ?

jamsesso commented 1 year ago

It does support nested objects.

Map<String, String> nested = Collections.singletonMap("B", "C");
Map<String, Object> data = Collections.singletonMap("A", nested);

As JSON this is {"A": {"B": "C"}}.

If you have a JSON string as your data, try converting to an Object using gson.fromJson.

grzegorz-taramina commented 1 year ago

It does support nested objects.

Map<String, String> nested = Collections.singletonMap("B", "C");
Map<String, Object> data = Collections.singletonMap("A", nested);

As JSON this is {"A": {"B": "C"}}.

If you have a JSON string as your data, try converting to an Object using gson.fromJson.

If I manually create map inside another map it works fine but I'm having issue passing any Object.

I tried example from the doc:

      val expression = "{\"*\": [{\"var\": \"y.nested\"}, 2]}"
      val data = Map("y" -> Map("nested" -> 555).asJava).asJava
      // Evaluate the result.
      val result = jsonLogic.apply(expression, data).asInstanceOf[Double]
      println(result)

Prints: 1110.0

This one works fine but when I parse using gson / directly pass Object it doesn't seem to properly read the data

      val expression = "{\"*\": [{\"var\": \"y.nested\"}, 2]}"
      val data = Map("y" -> new JavaNested(6)).asJava
      // Evaluate the result.
      val result = jsonLogic.apply(expression, data).asInstanceOf[Double]
      println(result)

Prints: 0.0

Am I missing something ?