javascriptjavajsonrhino

Retrieve javascript object in java with rhino


I want to get a javascript object from a javascript file, that only constists of this one big object. For example:

var cars = {
   mercedes: {
      colour: 'silver',
      drivemode: 'alldrive' 
   },

   audi: {
      size: '4x2x1,5m'
      speed: '220 kmph'
   }
};

For the javapart I am using rhino to get that object. For now I have coded:

Context context = context.enter();
context.setOptimizationLevel(9);
context.setLangaugeVersion(170);
context.getWrapFactory().setJavaPrimitiveWrap(false);

Scriptable defaultScope = context.initSafeStandardObjects();

So now i should have the possibility to be able to retrieve the javascript object. But how?

Script function = context.compileString("Any javascriptfunction as String", "javaScriptFile.js", 1, null);
function.exec(context, defaultScope);

But what would that javascript function look like to get that object as JSON (something like cars.stringify() )? And further more is that the right approach in using this function? And finally how and where to i save the object in a java Object?

i have already checked this post and this post also this post but all dont fit my criteria or are missing out on a code example for clarification

Edit: I have found another approach in calling/writing a javascript function in java as a string like:

Scriptable scriptObject;
private String functionAsString = "function getAsJson() {var objectString = { colour: \"silver\", drivemode: \"alldrive\" };return JSON.stringify(objectString);}";
Function fct = context.compileFunction(defaultScope, functionAsString, "AnyName", 1, null);
Object result = fct.call(context, defaultScope, scriptObject, null);

The only problem still standing is how do it get "objectString" to contain my cars.js? There somehow has to be a possibility to load that object in this variable

probably something like:

String functionAsString2 = "get cars() {return this.cars;}";

But how/and where do i specify the file in which to use this function?


Solution

  • I have found a way to retrieve the object by using the ScriptEngine from Rhino

    private ScriptEngineManager manager = new ScriptEngineManager();
    private ScriptEngine engine = manager.getEngineByName("JavaScript");
    
    engine.eval(Files.newBufferReader("PATH TO THE JAVASCRIPT FILE", StandardCharsets.UTF_8));
    
    Object result = engine.get("cars"); //Variable in the javascript File
    
    if(result instanceof Map){
    result = (Map<String,Object>) result;
    }
    

    so the object is retrieved and can be accessed and casted as a Map> and recursively accesed to in the end having a java Object of the JavaScript Object. No need to use functions