【问题标题】:Access Rhino's native JSON.Stringify from Java从 Java 访问 Rhino 的原生 JSON.Stringify
【发布时间】:2019-10-23 03:22:19
【问题描述】:

有没有比使用以下 kludge 更简洁的方法来获取 Javascript 对象的 JSON 表示?

System.out.println(((ScriptableObject) scope).callMethod(
    cx, (Scriptable) scope.get("JSON", scope), 
    "stringify", new Object[]{jsObject}));

其中 jsObject 是我要字符串化的 ScriptableObject。

【问题讨论】:

    标签: rhino


    【解决方案1】:

    请注意,Hannes 在 Rhino 中有 now addressed 这个。所以用法简化为:

    import org.mozilla.javascript.NativeJSON;
    // ...
    
    Object json = NativeJSON.stringify(cx, scope, jsObject, null, null);
    

    org.mozilla.javascript.NativeJSON 类在 Rhino 1.7R4 版本中应该是公开的。

    【讨论】:

    • 我想使用上面的,但我不知道如何从 Ant/Rhino/Script 标签中获取范围。上下文似乎可以通过 .getCurrentContext() 访问,但不确定范围。
    【解决方案2】:

    我能够使用 NativeJSON 类在 Apache Ant 目标中实现此功能。

    importPackage(org.mozilla.javascript);
    
    var context = Context.enter();
    var json = '{}';
    // The call to parse required a reviver function that should return the
    // state of a key/value pair.
    var reviver = function(key, value) { return value; };
    var scope = context.initStandardObjects();
    var object = NativeJSON.parse(context, scope, json, reviver);
    
    // The call to stringify does not require the replacer or space parameters.
    // The replacer is a function that takes a key/value pair and returns the
    // new value or an array of keys from the input JSON to stringify. The space
    // parameter is the indentation characters or length.
    json = NativeJSON.stringify(context, scope, config, null, 4);
    

    http://mozilla.github.io/rhino/javadoc/org/mozilla/javascript/NativeJSON.html https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/NativeJSON.java

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 2010-10-17
      • 1970-01-01
      • 2013-04-06
      • 2016-06-22
      • 2015-03-19
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      相关资源
      最近更新 更多