读取Java中的javascript对象 [英] Read javascript object in java
问题描述
我有一个如下的javascript对象.
I have a javascript object like follows.
{
"name": {
"type": "text",
"onClick": function () {
console.log("Hello");
}
}
}
它以字符串格式存储在Java中.
It is stored in string format in Java like.
String obj = "{ \"name\": { \"type\": \"text\", \"onClick\": function () { console.log(\"Hello\"); } } }";
我正在尝试寻找一种方法来读取Java中的obj并遍历对象图,就像我们使用JSON使用JSON一样(如果它没有函数声明的话).
I'm trying to figure out a way to read this obj in Java and traverse through the object graph like we can with JSON using Jackson if it didn't have function declaration.
是否有任何Java库可以读取/解析表示javascript对象(而不仅仅是JSON)的字符串并遍历对象图?
Is there any Java library to read/parse a string representing javascript object (not just JSON) and traverse through the object graph?
推荐答案
您可以使用Java的 JavaScript 内置.像
You could use Java's ScriptEngine
and the Javascript built-in. Something like,
String obj = "{'name':{'type': 'text', 'onClick': function (){console.log('Hello')}}}";
try {
ScriptEngine se = new ScriptEngineManager().getEngineByName("js");
se.eval(String.format("Object.bindProperties(this, %s);", obj));
se.eval("print(this.name.onClick)");
} catch (ScriptException e) {
e.printStackTrace();
}
可以读取函数声明(和其他任何obj
属性).
which can read the function declaration (and any of the other obj
properties).
这篇关于读取Java中的javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!