Skip to content

Commit

Permalink
Make loadable implement GSON serializers
Browse files Browse the repository at this point in the history
Just saves another class creation a this one has all the info needed
  • Loading branch information
KnightMiner committed Mar 21, 2024
1 parent eef05b7 commit fc53827
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/main/java/slimeknights/mantle/data/loadable/Loadable.java
@@ -1,7 +1,12 @@
package slimeknights.mantle.data.loadable;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.EncoderException;
Expand All @@ -14,14 +19,15 @@
import slimeknights.mantle.data.loadable.mapping.MappedLoadable;
import slimeknights.mantle.data.loadable.mapping.SetLoadable;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;

/** Interface for a generic loadable object */
@SuppressWarnings("unused") // API
public interface Loadable<T> {
public interface Loadable<T> extends JsonDeserializer<T>, JsonSerializer<T> {
/** Deserializes the object from json */
T convert(JsonElement element, String key) throws JsonSyntaxException;

Expand All @@ -48,6 +54,19 @@ default T getAndDeserialize(JsonObject parent, String key) {
void toNetwork(T object, FriendlyByteBuf buffer) throws EncoderException;


/* GSON methods, lets us easily use loadables with GSON adapters */

@Override
default T deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
return convert(json, type.getTypeName());
}

@Override
default JsonElement serialize(T object, Type type, JsonSerializationContext context) {
return serialize(object);
}


/* Fields */

/** Creates a required field from this loadable */
Expand Down

0 comments on commit fc53827

Please sign in to comment.