I have a javascript object like follows.
{
"name": {
"type": "text",
"onClick": function () {
console.log("Hello");
}
}
}
It is stored in string format in Java like.
String obj = "{ \"name\": { \"type\": \"text\", \"onClick\": function () { console.log(\"Hello\"); } } }";
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.
Is there any Java library to read/parse a string representing javascript object (not just JSON) and traverse through the object graph?
解决方案
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();
}
which can read the function declaration (and any of the other obj properties).