我正在尝试在nashorn引擎中存储JSON对象并按键获取值。
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.put("minimumBet", "{\"SEK\":\"1\",\"EUR\":\"2\"}");
//This prints {"SEK":"1","EUR":"2"}
System.out.println(engine.eval("minimumBet"));
//This assert fails
//engine.eval("minimumBet['SEK']") is retruning null
assertEquals(1, engine.eval("minimumBet['SEK']"));
请告诉我我错过了什么。
答案 0 :(得分:1)
engine.put(“minimumBet”,“{\”SEK \“:\”1 \“,\”EUR \“:\”2 \“}”);不会评估您在属性中放置的值,因此您只需设置一个字符串。您需要评估引擎内的字符串。
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) {
try {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.put("minimumBet", "{\"SEK\":1,\"EUR\":2}");
engine.eval("var bet = JSON.parse(minimumBet);");
engine.eval("var krona = bet['SEK'];");
engine.eval("var euro = bet['EUR'];");
Object krona = engine.get("krona");
Object euro = engine.get("euro");
System.out.println(krona + " " + krona.getClass());
System.out.println(euro + " " + euro.getClass());
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
}
收率:
1 class java.lang.Integer
2 class java.lang.Integer