I have just started developing applets. I want to be able to pass (JSON) data from a javascript function, to a method in my applet.
Although I have searched, I cannot find a suitable example that shows how to do this. Can someone please either show a link to a resource that shows how to do that, or paste a few lines in here to show how to do that.
Also, I have the ff questions:
On the JavaScript side, you should use JSON2 to convert your data to JSON text, using the code
var jsn = JSON.stringify({"x": "y"});
Then you pass it to the applet:
var applet = document.getElementById("myApplet");
applet.setJSONData(jsn);
You need, of course, to have a public method on your applet that you can call. On the Java side, you can use Jackson to parse the JSON to Java hashmaps or to beans:
public class MyApplet extends JApplet {
public void setJSONData(String data) {
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(data, Map.class);
// TODO sth with map
};
}
Be careful with encodings of non-ASCII characters, it seems that the JSON produced in the browser is not always UTF-8, it may depend on browser vendor or HTML page encoding.
If you are really adventurous you could experiment with JSObject in Java Plugin 2, instead of using JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With