Update: I was wrong naming a plain JavaScript object as “JSON object”. Thanks to guys who pointed it out in comments below. So I edited the question to avoid further misunderstanding.
I wonder whether calling JavaScript function with JavaScript object (that can be described as JSON string) as an argument using netscape.javascript.JSObject is possible from Java. I tried the following code snippet:
JSObject.getWindow(MyApplet.this).call(jsFunctionName, jsArgs);
According to this article Java objects are passed to named JavaScript function as is and will be automatically converted to some JavaScript primitives depending on context they are used in. Does it mean that it is impossible to pass a real JavaScript object described as some JSON string to JavaScript function and I have to look for a workaround like preparing a JSON string as java.lang.String argument in Java and then parsing it in JavaScript function to get a plain JavaScript object?
It is better to refer to chapter: «19.3 LiveConnect Data Conversion».
Every object passed within
jsArgsis wrapped with JavaObject wrapper. In fact it is the same JavaScript object with all public properties and methods of underlying object available.E.g. if I have folowing Java class:
And call JavaScript function:
JavaScript function could look like:
And you could convert it to JSON string like any other JavaScript object, if you want.
Instances of JSObject class passed as arguments to
callfunction will be converted to corresponding JavaScript objects. So, if you want to avoid JavaObject instaces occurence in your JavaScript code, you could try to create new JSObject instances like this:And add new properties:
Or like this:
To my mind, it will be more convenient to represent JavaScript objects within Java as maps, pass them to JavaScript as JSON strings using library like Gson, and convert them to JavaScript objects using JSON.parse().
Take a look at this Gson usage:
ImmutableMapandImmutableListare from Guava libraries.