这是我的代码:
JSONArray jsonArray = databaseQueryStatement.getJsonObject(query, connection);
String x= "item1has quantity of queryResult[0].quantity";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
Bindings params = engine.createBindings();
params.put("jsonArrayKey", jsonArray);
params.put("c", x);
String script = "var queryResult = JSON.parse(jsonArrayKey);"
+ "var resultedString = c";
engine.eval(script,params);
String result=(String) params.get("resultedString");
System.out.println(result);
当我传递值queryResult[0].quantity
而不是c
时,它会给我2
。但当我通过c
时,它正在打印:
item1has quantity of queryResult[0].quantity
我需要打印:
item1has quantity of 2
我该怎么做?我在这里使用java和nashorn引擎。
答案 0 :(得分:0)
您放入绑定的字符串无法作为脚本代码进行评估,因为它只是一个文字。
虽然如果您按照以下方式更改代码,我还没有明确您的意图,那么它会按照您的预期打印内容:
[...]
String x= "item1 has quantity of ";
[...]
String script = "var queryResult = JSON.parse(jsonArrayKey);"
+ "var resultedString = c + queryResult[0].quantity";
[...]
例如,更灵活的解决方案可能如下:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Bindings params = engine.createBindings();
params.put("jsonArrayKey", "[{\"quantity\":2},{\"quantity\":3}]");
params.put("msg", "item <ID> has quantity of <VALUE>");
params.put("index", 0);
String script = "var queryResult = JSON.parse(jsonArrayKey);\n"
+ "var resultedString = msg.replace('<ID>', index + 1).replace('<VALUE>', queryResult[index].quantity);";