Reflection Permission problems when using the GSON

2019-05-10 18:35发布

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.

2条回答
beautiful°
2楼-- · 2019-05-10 19:08

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;
        }
    });
}
查看更多
何必那么认真
3楼-- · 2019-05-10 19:12

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.

查看更多
登录 后发表回答