4

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?

TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125

3 Answers3

3

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).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

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;
    }
}
Neel
  • 86
  • 3
  • Jackson is working only for JSON. i.e without function declarations. – TheKojuEffect Jan 08 '16 at 05:47
  • The point is if JSON string is just a key value pair. by this you will get your function as a value to the key 'onClick'. I.e a string. If you need a function to be parsed. you need to look for javascript parser implementation in java . – Neel Jan 08 '16 at 06:00
0

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"
    }
}
botem
  • 348
  • 1
  • 11