Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Gson Preconditions fail in this instance?

I am writing a deserializer for the class ForeignCollection, which is abstract, and provided to me in the ORMLite Android Library. See my code below.

public class ForeignCollectionDeserializer implements JsonDeserializer<ForeignCollectionDeserializer> {
    @Override
    public ForeignCollection deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        ...
    }
}

I have also tried implementing JsonDeserializer<?> and JsonDeserialzer (with no generic type)

I'm using GsonBuilder.registerTypeAdapter to register the deserializer.

GsonBuilder gb = new GsonBuilder();

gb.registerTypeAdapter(ForeignCollection.class, new ForeignCollectionDeserializer());
Gson gson = gb.create();

However, registerTypeAdapter() is throwing this:

06-11 11:27:27.937: E/AndroidRuntime(15197): FATAL EXCEPTION: main
06-11 11:27:27.937: E/AndroidRuntime(15197): Process: com.myapp, PID: 15197
06-11 11:27:27.937: E/AndroidRuntime(15197): java.lang.IllegalArgumentException
06-11 11:27:27.937: E/AndroidRuntime(15197):    at com.google.gson.internal.$Gson$Preconditions.checkArgument($Gson$Preconditions.java:42)
06-11 11:27:27.937: E/AndroidRuntime(15197):    at com.google.gson.GsonBuilder.registerTypeAdapter(GsonBuilder.java:448)

I am stepping through the code and I get to the offending piece, from GsonBuilder below.

public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
    $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
            || typeAdapter instanceof JsonDeserializer<?>
            || typeAdapter instanceof InstanceCreator<?>
            || typeAdapter instanceof TypeAdapter<?>);
    if (typeAdapter instanceof InstanceCreator<?>) {
        instanceCreators.put(type, (InstanceCreator) typeAdapter);
    }

I evaluated typeAdapter instanceof JsonDeserializer<?> in debug mode and found that it is actually false

Actually I've evaluated all of these:

  • typeAdapter instanceof JsonDeserializer
  • typeAdapter instanceof JsonDeserializer<ForeignCollection>
  • typeAdapter instanceof JsonDeserializer<?>

They are all false.

How is this so, when I have declared typeAdapter as an Object of type ForeignCollectionsDeserializer, which implements JsonDeserializer?

like image 654
tyler Avatar asked Mar 26 '26 14:03

tyler


1 Answers

It turns out that I had multiple incorrect imports.

I was accidentally importing another libraries implementation of Gson's JsonDeserializer, which caused the code to compile, but fail the instanceof conditional.

smh

like image 93
tyler Avatar answered Mar 29 '26 04:03

tyler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!