Created
March 19, 2018 15:43
-
-
Save HaedHutner/6c2ead4260d3e1b3c720377a53309338 to your computer and use it in GitHub Desktop.
Abstract Gson TypeAdapter for Configurate + Implementation class
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 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; | |
} | |
} |
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 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