Java: Using Gson in an Applet causes SecurityException

前端 未结 3 1257
醉酒成梦
醉酒成梦 2021-01-21 18:27

I\'m trying to use Google Gson in my Java Applet, but when I do I get

Exception in thread \"Thread-19\" java.security.AccessControlException: access deni

相关标签:
3条回答
  • 2021-01-21 19:03

    Further to @Chrizzz, I'm doing two way command object exchange between a Java web server and an unsigned applet. As such I am using both Gson toJson() and fromJson() within my applet code.

    I've found that both deserialization and serialization in an unsigned applet throw security exceptions and that implementing custom serializers and deserializers can work-around those problems.

    The biggest pain is not being able emulate the applet environment (SecurityManager) for Unit testing. It seems that there are no frameworks available to do this: see e.g. How to unit test Java code that is expected to run within an applet Security Manager

    0 讨论(0)
  • 2021-01-21 19:08

    I have found the answer here.

    System.setSecurityManager(null);
    

    Adding to static main helped me. Of course, all-permissions in jnlp and so on must be.

    0 讨论(0)
  • 2021-01-21 19:16

    I solved this problem using a custom deserializer.

    I had a class with two members, a timestamp and a list of doubles. This is the code that worked for me.

    GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(TimestampedValueList.class, new JsonDeserializer<TimestampedValueList>() {
            @Override
            public TimestampedValueList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                long timestampMs = json.getAsJsonObject().get("timestampMs").getAsLong();
                double[] valueList = context.deserialize(json.getAsJsonObject().get("valueList"), double[].class);
                return new TimestampedValueList(timestampMs, valueList);
            }
        });
    gson = gsonBuilder.create();
    

    Hope this can help anyone!

    0 讨论(0)
提交回复
热议问题