2

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?

Chir
  • 671
  • 1
  • 10
  • 29

1 Answers1

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.

  • GSON can work only if the returned object has attributes defined in them, which is not the case here. The script.eval() method returns NativeObject. GSON will not be useful here! – Chir Feb 28 '14 at 10:55
  • @Chir You can try then to use code reflection (getDeclaredFields) to ask the object for its attributes. – Pablo Francisco Pérez Hidalgo Feb 28 '14 at 10:58
  • Unfortunately the object of type NativeObject doesn't give me correct information about attributes it has. – Chir Feb 28 '14 at 11:35
  • @Chir Doesn't object.getClass() list the JSON fields? If the answer is it doesn't then my approach is useless. Did you try to specify the Bindings at **eval** call. – Pablo Francisco Pérez Hidalgo Feb 28 '14 at 11:38
  • I think we are on different plane. I can NOT use GSON library as it can only parse valid JSON. What I am trying to do is to execute a JavaScript function, using java 6. The function returns an object which in Java is a NativeObject. This object doesn't have any json attributes as its fields. It's structure is quite different. – Chir Feb 28 '14 at 12:12
  • 1
    @Chir I have just copied your code into an editor and played with it: NativeObject o = (NativeObject)script.eval(); for(Object cf: o.getAllIds()) System.out.println("F: " + cf.toString() + "-----" + o.get(cf.toString()).toString()); Why Don't you use this code to build your JSON, the only difficulty is to manage nested objects but it can be done easily using a recursive algorithm – Pablo Francisco Pérez Hidalgo Feb 28 '14 at 12:20
  • Thanks for quick response. I agree this would work. However, I need to form json out of it. I was wondering if JDK provides such a feature and I can utilize it as a library :) – Chir Feb 28 '14 at 12:23
  • Yes, writing recursive algorithm would be easy. I wonder that JDK doesn't have such an API to convert Java object back to JSON string. – Chir Feb 28 '14 at 12:27