Search code examples
javascriptjavajsonnashorn

Nashorn/Javascript associative array to Java object?


I'm trying to integrate the JavaScript in my Wicket project into my TestNG test suite. I decided to give project Nashorn a try.

Now I want to parse results from nashorn. I return an associative array from javascript, and get a ScriptObjectMirror as returned type.

ScriptEngine engine = factory.getEngineByName( "nashorn" );
String content = new String( Files.readAllBytes( Paths.get( "my-funcs.js" ) ) );
Object result = engine.eval( content + ";" + script );

Of course, I can JSON.stringify the array, using more javascript script, and parse it back using Gson or similar libraries, but is there a more native approach to this mapping problem?


Solution

  • Thanks to the above comments, I found a relatively nice solution, using Apache Commons BeanUtils

    public static class MyResult
    {
        private String prop1;
        public void setProp1(String s)
        {
            ...
        }
    }
    
    ...
    
    public MyResult getResult(String script)
    {
        //ugly-but-fast-to-code unchecked cast
        ScriptObjectMirror som = (ScriptObjectMirror) engine.eval(script);    
        MyResult myResult = new MyResult();
        BeanUtils.populate(myResult, som);
        return myResult;
    }