Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An example of a javascript function passing JSON data to a Java applet

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:

  1. is there a limit to the size of JSON string that can be passed from JSON to the applet? (if yes - what is it?)
  2. Is it possible to compress (zip) a long string before passing it from JSON to the applet?
like image 475
oompahloompah Avatar asked Nov 05 '22 06:11

oompahloompah


1 Answers

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.

like image 183
Eero Avatar answered Nov 09 '22 02:11

Eero