Retrieve object returned by JavaScript in Java

时间秒杀一切 提交于 2021-02-10 04:55:14

问题


By using JavaScript APIs in Java 7, I am able to compile and invoke JavaScript functions. The issue is with value returned by the JavaScript function. Simple types can be type-cast easily. However, if a JavaScript function returns an object. How to convert the returned object into json string?

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine se = mgr.getEngineByName("JavaScript");
    if (se instanceof Compilable) {
        Compilable compiler = (Compilable) se;
        CompiledScript script = compiler
                .compile("function test() { return { x:100, y:200, z:150 } }; test();");
        Object o = script.eval();
        System.out.println(o);
    } else {
        System.out.println("Engine cann't compile code.");
    }

How to convert object returned by JavaScript to JSON string?


回答1:


Maybe Google JSON libraries for Java (GSON) will be useful for you:

https://code.google.com/p/google-gson/

You can use them to seriazlize/deserialize to objects as long as you deffine their classes with the proper getters and setters which have to match with the Bindings you shoud specify at eval call.

If you need to inspect the returned object attributes before serializing, deffine a class similar to this one.

public class Serializer {
    static public Map<String, Object> object2Map(NativeObject o)
    {
        Map<String, Object> ret = new HashMap<>();
        for(Object keyField: o.getAllIds())
        {
            try {
                Object valObject = o.get(keyField.toString());
                ret.put(keyField.toString(), valObject);
            } catch (Exception e) {
                continue; 
            }
        }
        return ret;
    }
}

And use it to map the object attributes in a map.

The idea is to iterate over the object attributes and then generate an object of a specific class which can be used by GSON or generate the JSON string by yourself.



来源:https://stackoverflow.com/questions/22092662/retrieve-object-returned-by-javascript-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!