Skip to content

Instantly share code, notes, and snippets.

@HaedHutner
Created March 19, 2018 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HaedHutner/6c2ead4260d3e1b3c720377a53309338 to your computer and use it in GitHub Desktop.
Save HaedHutner/6c2ead4260d3e1b3c720377a53309338 to your computer and use it in GitHub Desktop.
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