gsonBuilder.registerTypeAdapterFactory(new ClassTypeAdapterFactory());
Created
August 9, 2020 12:48
-
-
Save afiqiqmal/feb72371e5f714b0669e97450dfbbf18 to your computer and use it in GitHub Desktop.
GSON Class Type Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ClassTypeAdapter extends TypeAdapter<Class<?>> { | |
@Override | |
public void write(JsonWriter jsonWriter, Class<?> clazz) throws IOException { | |
if(clazz == null){ | |
jsonWriter.nullValue(); | |
return; | |
} | |
jsonWriter.value(clazz.getName()); | |
} | |
@Override | |
public Class<?> read(JsonReader jsonReader) throws IOException { | |
if (jsonReader.peek() == JsonToken.NULL) { | |
jsonReader.nextNull(); | |
return null; | |
} | |
Class<?> clazz = null; | |
try { | |
clazz = Class.forName(jsonReader.nextString()); | |
} catch (ClassNotFoundException exception) { | |
throw new IOException(exception); | |
} | |
return clazz; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ClassTypeAdapterFactory implements TypeAdapterFactory { | |
@Override | |
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { | |
if(!Class.class.isAssignableFrom(typeToken.getRawType())) { | |
return null; | |
} | |
return (TypeAdapter<T>) new ClassTypeAdapter(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment