Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Abstract Gson TypeAdapter for Configurate + Implementation class
public abstract class AbstractConfigurateAdapter<T> extends TypeAdapter<T> {
private Class<T> clazz;
private JsonParser parser = new JsonParser();
protected AbstractConfigurateAdapter ( Class<T> clazz ) {
this.clazz = clazz;
}
@Override
public void write( JsonWriter out, T value ) throws IOException {
GsonConfigurationLoader loader = GsonConfigurationLoader.builder().build();
try {
ConfigurationNode node = loader.createEmptyNode().setValue( TypeToken.of( clazz ), value );
StringWriter writer = new StringWriter();
loader.saveInternal( node, writer );
String json = writer.toString();
//therysCore.getInstance().getLogger().info( "Write: " + json ); // DEBUG
out.jsonValue( json );
} catch ( ObjectMappingException e ) {
e.printStackTrace();
}
}
@Override
public T read( JsonReader in ) throws IOException {
String json = parser.parse( in ).toString();
//AtherysCore.getInstance().getLogger().info( "Read: " + json ); // DEBUG
GsonConfigurationLoader loader = GsonConfigurationLoader.builder().setSource( () -> new BufferedReader( new StringReader( json ) ) ).build();
ConfigurationNode node = loader.load();
try {
return node.getValue( TypeToken.of( clazz ) );
} catch ( ObjectMappingException e ) {
e.printStackTrace();
}
return null;
}
}
public class ConfigurateAdapter<T> extends AbstractConfigurateAdapter<T> {
public ConfigurateAdapter( Class<T> clazz ) {
super( clazz );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment