Search code examples
javanashorn

Parse in Java accessible in Java


I have

public JSONObject parseXML(String xml) {
    JSONObject jsonObject = XML.toJSONObject(xml);
    return jsonObject;
}

from the org.json library.

In Nashorn I want to be able to do

let foo = parseXML(someXMLString);
console.log(foo.someProperty);

What I end up getting is a NPE. But if I do

let foo = parseXML(someXMLString);
console.log(JSON.parse(foo.someProperty));

it works. is there an equivalent function to JSON.parse I can do in Java land and return without needing that JSON.parse in JavaScript?

edit: Please note it is NOT a duplicate. I am not asking how to parse for certain values in the JSON, I am asking how to return the entire object, so that it is parseable by Nashorn without the extra JSON.parse


Solution

  • You can call JSON.parse or any other script function from Java. Example code to call JSON.parse from Java:

    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import jdk.nashorn.api.scripting.JSObject;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            ScriptEngineManager m = new ScriptEngineManager();
            ScriptEngine e = m.getEngineByName("nashorn");
    
            // get ECMAScript JSON.parse
            JSObject jsonParse = (JSObject)e.eval("JSON.parse");
    
            // initialize/retrieve JSON string here
            String str = "{ \"foo\": 42, \"bar\": { \"x\": \"hello\" } }";
    
            // call JSON.parse from Java
            Object parsed = jsonParse.call(null, str);
    
            // expose parsed object to script
            e.put("obj", parsed);
    
            // access parsed object from script
            e.eval("print(obj.foo)");
            e.eval("print(obj.bar.x)");
        }
    }