最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Rhino: return JSON from within Java - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Jun 1, 2012 at 19:19 parsaparsa 2,6683 gold badges35 silver badges44 bronze badges 3
  • Since you answered your own question, and the answer was in another question, I would remend deleting your question. – smcg Commented Jun 1, 2012 at 19:23
  • questions/answers are slightly different (parse vs. stringify). what to do? – parsa Commented Jun 1, 2012 at 19:25
  • post your own answer and accept it, then. Since you already posted an answer, you just have to accept it. – smcg Commented Jun 4, 2012 at 13:41
Add a ment  | 

3 Answers 3

Reset to default 10

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());

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./mozilla/rhino/blob/master/src/org/mozilla/javascript/NativeJSON.java#L110.

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);
发布评论

评论列表(0)

  1. 暂无评论