How to convert Java Pojo to Nashorn Json?

3.3k views Asked by At

I have a Java object that I want to turn into a json object and pass to the Nashorn javascript engine. It is surprisingly difficult to google an answer for this! Can someone tell me how to do it?

I tried this:

ObjectMapper mapper = new ObjectMapper();
String inputModelAsString = mapper.writeValueAsString(inputModel);

And then passing the string json to the function:

result = invocable.invokeFunction(PROGRAM_FUNCTION, moduleName, inputModelAsString);

But it was passed as a string, not as a json.

3

There are 3 answers

2
Avinash On BEST ANSWER

You can convert json from engine by

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("("+inputModelAsString+")");

Then you can pass the json object in you code

result = invocable.invokeFunction(PROGRAM_FUNCTION, moduleName, json);
0
jatanp On

you could use inbuild JSON feature in Nashorn as mentioned in

Nashorn JSON stringify

0
Fábio On

I faced a similar issue and handled it in a slightly different way.

I wouldn't access the class ScriptObjectMirror directly as it's part of the internal Nashorn's API and therefore prone to change.

You may try something like this:

engine.eval("var inputModel = " + inputModel + ";");    
Object json = engine.get("inputModel");