Skip to content Skip to sidebar Skip to footer

Retrieve Object Returned By Javascript In Java

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

Solution 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.

publicclassSerializer {
    staticpublicMap<String, Object> object2Map(NativeObject o)
    {
        Map<String, Object> ret = newHashMap<>();
        for(ObjectkeyField: 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.

Post a Comment for "Retrieve Object Returned By Javascript In Java"