【问题标题】:Read the javascript data读取 javascript 数据
【发布时间】:2016-06-16 08:06:16
【问题描述】:

关于下面的java脚本,我想在java类中读取employees变量。你能帮我解决这个问题吗?

var employees = {
   accounting: []
};

for(var i in someData) {
   var item = someData[i];

   employees.accounting.push({ 
      "firstName" : item.firstName,
      "lastName"  : item.lastName,
      "age"       : item.age 
   });
}

【问题讨论】:

    标签: javascript java json


    【解决方案1】:

    如果您使用的是 java6 或 java7 你可以在 java 中获取 javascript 变量,如下所示:

    (NativeObject 在 java8 中已被移除,但有一个类似的类 [jdk.nashorn.api.scripting.ScriptObjectMirror] 可以使用)

    public class Test5 {
        private static final String TEST_SCRIPT =
                "var employees = {"
                + " accounting: []"
                + "};"
                + "for(i=1; i<=3; i++) {"
                + " employees.accounting.push({ "
                + " \"firstName\" : \"firstName\" + i,"
                + " \"lastName\"  : \"lastName\" + i,"
                + " \"age\"       : \"age\" + i"
                + "});"
                + "}"
                + "employees;";
        /**
         * @param args
         */
        public static void main(String[] args) {
            try{
                CompiledScript script = compEngine.compile(TEST_SCRIPT);
                NativeObject obj = (NativeObject) script.eval();
                NativeArray obj1 = (NativeArray) obj.get(obj.getAllIds()[0]);
                for (Object temp : obj1) {
                    NativeObject obj2 = (NativeObject) temp;
                    System.out.println(obj2.get("firstName"));
                    System.out.println(obj2.get("lastName"));
                    System.out.println(obj2.get("age"));
                }
            }catch(Exception e){e.printStackTrace();}
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-22
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多