用Java,Javascript对象解析Javascript

时间:2012-10-13 13:56:55

标签: java javascript rhino

我正在尝试使用Java中的ScriptEngine解析Javascript文件。我对执行脚本不感兴趣,只是解析它以获得一些值。

脚本文件由一系列具有以下结构的数组组成:

var array= new Array();
array[0]=new Array();
array[0]['point']=new Point2D(2.454,-8.33);
array[0]['name']='Object 1';
array[1]=new Array();
array[1]['point']=new Point2D(42.84, 3.53);
array[1]['name']='Object 2';

...

将Point2D定义为:

function Point2D(x,y) {
this.x = x;
this.y = y;
}

到目前为止,我已使用以下代码解析了脚本:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine se = mgr.getEngineByName("JavaScript");
try {
  se.eval(file);
  NativeArray array = (NativeArray)se.get("array");
  for(int i = 0; i < array.getLength(); i++){
    if(array.get(i)!=null){
      NativeArray elementArray = (NativeArray)array.get(i);
      System.out.println("Object: " + elementArray);
      System.out.println("name: " + elementArray.get("name", elementArray));
      System.out.println("point: " +  elementArray.get("point", elementArray));
    }
  }
}
catch (ScriptException e) {
      ....
}

这给了我正确的名字,但我得到了Point2D项目的Object类实例。由于它最初是一个javascript对象,我如何解析它以获取x和y值?

2 个答案:

答案 0 :(得分:1)

好吧,多亏了@Pointy我找到了解决方案,我在if语句中注入了这段代码:

se.eval("var x = array[" + i + "]['point'].x; var y = array[" + i + "]['point'].y;", se.getBindings(ScriptContext.ENGINE_SCOPE));

答案 1 :(得分:1)

你可以这样做:

    NativeObject point;
    NativeArray elementArray;
    for(int i = 0; i < array.getLength(); i++){
        if(array.get(i)!=null){
            elementArray = (NativeArray)array.get(i);                
            System.out.println("name: " + elementArray.get("name", elementArray));
            point = (NativeObject) arrayFirstElement.get("point", arrayFirstElement);
            //System.out.println("point.x: " +  NativeObject.getProperty(point, "x"));
            //System.out.println("point.y: " +  NativeObject.getProperty(point, "y"));
            System.out.println("object point has: ");
            for ( Object propertyId : NativeObject.getPropertyIds(point)){
                System.out.println("property "+ propertyId + " has value " + NativeObject.getProperty(point, propertyId.toString()));
            } 
        }
    }

但是看看这些教程:12,你可能会得到一些新的想法:)