0

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

larz
  • 5,724
  • 2
  • 11
  • 20
MaxPower
  • 881
  • 1
  • 8
  • 25
  • Possible duplicate of [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – James May 15 '17 at 21:09
  • `public static JSONObject parseXML(String xml)` and `YourClass.parseXML` – Joop Eggen May 15 '17 at 21:39
  • Sorry I omitted that for brevity. I have the bindings setup that map to this class. The method is being called and returning this object. I just have to call a JSON.parse on the object returned. I want to be able to omit that. – MaxPower May 15 '17 at 21:44

1 Answers1

1

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)");
    }
}
A. Sundararajan
  • 4,277
  • 1
  • 15
  • 30