javajsonspringexpression-evaluation

Parsing JSON and Evaluating expressions from its fields


I have a JSON document from which I have figured a way of parsing and extracting the values within it using the library of JSON-Path

I have to evaluate rules/expressions using the variables in the parsed JSON.

For example:

{maxAge:25, minAge:20, age:25}

  • rule1 : $.maxAge-$.minAge>100 then send alert
  • rule2 : $.age<18 then send alert

What libraries are available in Java for the same ?


Solution

  • Figured out a way, apparently, I don't need a JSON path. I can use javascript directly inside my code. so I've written rules in javascript

    public static void main(String[] args) {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
            String json = "{\"maxAge\":25, \"minAge\":20, \"age\":25}";
            String rule = "(x.maxAge)-(x.minAge) > 0;";
    
            jsEngine.put("x", json);
    
            try {
                jsEngine.eval("function test(abc){" + "var x=JSON.parse(abc);" + "return " + rule + "}");
    
                Invocable inv = (Invocable) jsEngine;
                boolean result = (Boolean) inv.invokeFunction("test", json);
                if (result) {
                    System.out.println("Alert rule triggered");
                }
    
            } catch (ScriptException ex) {
                ex.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
    
        }