Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GsonBuilder registerTypeAdapter method throws IllegalArgumentException

Tags:

java

android

gson

I am calling a method this way:

GsonBuilder gsonBuilder = new GsonBuilder()
        .registerTypeAdapter(CoindeskRateResult.class, CurrencyRateDeserializer.class)

CurrencyRateDeserializer is a com.google.gson.JsonDeserializer

import com.google.gson.JsonDeserializer;

    public class CurrencyRateDeserializer implements JsonDeserializer<CoindeskRateResult> {
        @Override
        public CoindeskRateResult deserialize(JsonElement json, Type typeOfT,
                                              JsonDeserializationContext context)
                throws JsonParseException {
            CoindeskRateResult result = new CoindeskRateResult();
            return result;
        }
    }

The error occurs in the GsonBuilder class. I know that typeAdapter is an instance of JsonDeserializer<?> but $Gson$Preconditions.checkArgument throws an IllegalArgumentException

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

StackTrace:

*Caused by: java.lang.IllegalArgumentException
                at com.google.gson.internal.$Gson$Preconditions.checkArgument($Gson$Preconditions.java:46)
                at com.google.gson.GsonBuilder.registerTypeAdapter(GsonBuilder.java:472)*
    .....

My CoindeskRateResult class:

public class CoindeskRateResult {
    public Map<String, String> data = new HashMap<>();
}
like image 728
Nariman Ermekov Avatar asked Nov 22 '18 13:11

Nariman Ermekov


1 Answers

This is wrong:

.registerTypeAdapter(CoindeskRateResult.class, CurrencyRateDeserializer.class)

This is why all of the instanceof checks fail for the first case. What you're looking for is:

.registerTypeAdapter(CoindeskRateResult.class, new CurrencyRateDeserializer())

To be honest, I think this is a Gson design flaw.

like image 84
user10691903 Avatar answered Nov 08 '22 18:11

user10691903