views:

112

answers:

2

I'm writing an Applet that makes some JSON-RPC calls. I'm using the Google JSON library (GSON) to cast the response JSON into a class. Thsi seems to work fine as is but when I use this code in my Applet, I'm hit with a java.lang.reflect.reflectpermission. From what I read on this thread on SO, it seems that since GSON uses Reflection, I cannot use it in Applets unless I explicitly modify the security policy. How can I get around this? I've created a bunch of classes in my application and was using the Gson.fromJson method to cast it into the class. Is there any way to achieve the same functionality without having to re-write half my code.

(The complexity of dealing with JSON in Java seems to be in a league of its own!)

Thanks in advance guys.

A: 

Apart from signing the applet, you could try to execute this in AccessController#doPrivileged():

public void init() {
    AccessController.doPrivileged(new PrivilegedAction<Object> {
        @Override public Object run() {
            // Put your original init() here.
            return null;
        }
    });
}
BalusC
+1  A: 

Some JSON libraries for Java are indeed mind numbingly complex especially considering the simplicity of JSON itself. In my opinion http://www.json.org/java/index.html is the best library and doesn't do any fancy tricks, just parses the JSON into its own special structure and that's it. This of course means you have to make specific code to turn the JSON Object hierarchy to something you use but that shouldn't be that hard.

GSON is more about JSON-based persistence in the vein of XStream (which can do JSON too) and sounds a bit too heavyweight for just an Applet.

Esko
Hi Esko. It seems to be quite easy to write JSON using the JSON.org library but parsing the JSON back to Objects seems to be quite hard. I can't seem to find any good examples. Could you point me into the right direction - a tutorail/documents on parsing JSON into a JSONObject. Thanks
Mridang Agarwalla
@mridang: Using the JSON library I linked, `JSONObject parsed = new JSONObject(yourJSONContentAsString);`. Yep, simple as that.
Esko