Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top