Rhino: return JSON from within Java

余生颓废 提交于 2019-12-02 03:53:08

问题


I have the string representation of a JSON-serialized object in Java e.g. "{\"name\":\"John\",\"age\":24}". How do I parse and return it to the JavaScript context, just the way JSON.parse(str) would work in JS? Thanks.


回答1:


The latest version of Rhino has only four args, and the fourth cannot be null. To solve this, you must create a simple class that implements org.mozilla.javascript.Callable:

import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

public class NullCallable implements Callable
{
    @Override
    public Object call(Context context, Scriptable scope, Scriptable holdable, Object[] objects)
    {
        return objects[1];
    }
}

You can then call NativeJSON.parse like this:

Object result = NativeJSON.parse(context, scope, jsonString, new NullCallable());



回答2:


Found the answer here: Access Rhino's native JSON.Stringify from Java

import org.mozilla.javascript.NativeJSON;

Object json = NativeJSON.parse(cx, scope, str, null, null);



回答3:


Another way to do it is by calling org.mozilla.javascript.json.JsonParser.parseValue. That is if you don't need to apply a reviver.

More interestingly, org.mozilla.javascript.NativeJSON is built around org.mozilla.javascript.json.JsonParser.parseValue. And you can see that here, https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/NativeJSON.java#L110.



来源:https://stackoverflow.com/questions/10856154/rhino-return-json-from-within-java

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