问题
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?
回答1:
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).
回答2:
You can use object mapper from jackson libarary to convert jsonString to hash map
import com.fasterxml.jackson.databind.ObjectMapper;
private Map<String, Object> getMapFromJson(String json){
Map<String,Object> map = new HashMap<String,Object>();
ObjectMapper mapper = new ObjectMapper();
try {
//convert JSON string to Map
map = mapper.readValue(String.valueOf(json), new TypeReference<Map<String, Object>>() {} );
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
回答3:
I suggest library org.json : JavaDoc URL, jar file Download
[Example]
String obj = "{ \"name\": { \"type\": \"text\", \"onClick\": function () { console.log(\"Hello\"); } } }";
JSONObject json = new JSONObject(obj);
JSONObject subJson = new JSONObject();
if( ! json.isNull("name") ){ //Determine if the value associated with the key("name") is null or if there is no value.
subJson = json.getJSONObject("name");
if( ! subJson.isNull("type") ){ // Determine if the value associated with the key("type") is null or if there is no value.
subJson.getString("type"); // get the value : "text"
subJson.put("newData", "text2"); // data added under the "onclick"
}
}
来源:https://stackoverflow.com/questions/34670142/read-javascript-object-in-java