检索Java中JavaScript返回的对象 [英] Retrieve object returned by JavaScript in Java

查看:71
本文介绍了检索Java中JavaScript返回的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用Java 7中的JavaScript API,我可以编译和调用JavaScript函数.问题在于JavaScript函数返回的值.简单类型可以很容易地进行类型转换.但是,如果JavaScript函数返回一个对象.如何将返回的对象转换为json字符串?

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.");
    }

如何将JavaScript返回的对象转换为JSON字符串?

How to convert object returned by JavaScript to JSON string?

推荐答案

也许Java的Google JSON库(GSON)对您有用:

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

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

您可以使用它们对对象进行序列化/反序列化,只要您使用必须与在 eval 中指定的 Bindings 相匹配的适当的getter和setter定义它们的类即可. strong>通话.

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.

想法是遍历对象属性,然后生成特定类的对象,该类可以由GSON使用,也可以自己生成JSON字符串.

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.

这篇关于检索Java中JavaScript返回的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆