Reputation: 4110
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?
Upvotes: 0
Views: 2041
Reputation: 5124
It is better to refer to chapter: «19.3 LiveConnect Data Conversion».
Every object passed within jsArgs
is 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:
public class MyJavaClass {
public String name;
public int number;
public MyJavaClass(String n, int i) {
name = n;
number = num;
}
}
And call JavaScript function:
JSObject.getWindow(MyApplet.this).call("abFunc", new MyJavaClass("Kolya", 500));
JavaScript function could look like:
var abFunc = function(obj){
numberPlusThousand = (1000 + obj.number);
name = String(obj.name);
...
};
And you could convert it to JSON string like any other JavaScript object, if you want.
Instances of JSObject class passed as arguments to call
function 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:
JSObject myJsObj = (JSObject) JSObject.eval("{}");
And add new properties:
myJsObj.setMember("name", JSObject.eval("'Kolya'"));
myJsObj.setMember("number", 500);
Or like this:
myJsObj.eval("self.name = 'Kolya'");
myJsObj.eval("self.number = 500");
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:
Map m1 = ImmutableMap.of("id", "Kolya", "num", 500);
Map m2 = ImmutableMap.of("marks", new byte[] {5, 4, 5, 3});
Map m = ImmutableMap.of("m1", m1, "m2", m2, "l", ImmutableList.of("str", 234L, false));
System.out.println(new Gson().toJson(m));
// {"m1":{"id":"Kolya","num":500},"m2":{"marks":[5,4,5,3]},"l":["str",234,false]}
ImmutableMap
and ImmutableList
are from Guava libraries.
Upvotes: 2