Nashorn/Javascript 关联数组到 Java 对象?
Nashorn/Javascript associative array to Java object?
我正在尝试将我的 Wicket 项目中的 JavaScript
集成到我的 TestNG
测试套件中。我决定尝试 Nashorn 项目。
现在我想解析来自 nashorn 的结果。我 return 来自 javascript 的关联数组,并得到 ScriptObjectMirror
作为 returned 类型。
ScriptEngine engine = factory.getEngineByName( "nashorn" );
String content = new String( Files.readAllBytes( Paths.get( "my-funcs.js" ) ) );
Object result = engine.eval( content + ";" + script );
当然,我可以 JSON.stringify
数组,使用更多 javascript 脚本,然后使用 Gson
或类似的库解析它,但是有没有更原生的方法呢映射问题?
感谢上面的评论,我找到了一个比较好的解决方案,使用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;
}
我正在尝试将我的 Wicket 项目中的 JavaScript
集成到我的 TestNG
测试套件中。我决定尝试 Nashorn 项目。
现在我想解析来自 nashorn 的结果。我 return 来自 javascript 的关联数组,并得到 ScriptObjectMirror
作为 returned 类型。
ScriptEngine engine = factory.getEngineByName( "nashorn" );
String content = new String( Files.readAllBytes( Paths.get( "my-funcs.js" ) ) );
Object result = engine.eval( content + ";" + script );
当然,我可以 JSON.stringify
数组,使用更多 javascript 脚本,然后使用 Gson
或类似的库解析它,但是有没有更原生的方法呢映射问题?
感谢上面的评论,我找到了一个比较好的解决方案,使用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;
}