java nashorn 引擎对象内嵌json字符串时JSON.parse的bug

假设预置了:json = "{\"name\": \"jack\", \"age\": 24}",在java中使用nashorn引擎执行以下代码块:

var obj = JSON.parse(json);
print(obj.name);
for (var key in obj) {
    print(key + ":" + obj[key]);
}

具体java代码为:

    public static void main(String[] args) throws Exception{
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");

        String json = "{\"name\": \"jack\", \"age\": 24}";
        scriptEngine.put("json", json);

        String js01 = "var obj = JSON.parse(json);print(obj.name);for(var key in obj) {print(key + \":\" + obj[key]);}";
        scriptEngine.eval(js01);
    }

结果一切正常:


但是如果这个预置的json字符串是在一个java对象中时,会报bug:
假设我们有一个request对象,这个对象有一个json字段,而这个json字段的值为"{\"name\": \"jack\", \"age\": 24}",然后执行以下javascript代码:

request.json = JSON.parse(request.json);
print(request.json);
for (var key in request.json) {
    print(key + ":" + request.json[key]);
}

具体执行的java代码为:

    public static void main(String[] args) throws Exception{
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
        
        String json = "{\"name\": \"jack\", \"age\": 24}";
        Request request = new Request();
        request.setJson(json);
        scriptEngine.put("request", request);

        String js01 = "request.json = JSON.parse(request.json);print(request.json);for(var key in request.json) {print(key + \":\" + request.json[key]);}";

        scriptEngine.eval(js01);
    }

结果异常:


解决办法:暂未找到解决方法

你可能感兴趣的:(java nashorn 引擎对象内嵌json字符串时JSON.parse的bug)