Respackopts/src/main/java/io/gitlab/jfronny/respackopts/gson/entry/NumericEntrySerializer.java
2021-10-03 16:45:29 +02:00

53 lines
2.5 KiB
Java

package io.gitlab.jfronny.respackopts.gson.entry;
import com.google.gson.*;
import io.gitlab.jfronny.respackopts.data.entry.ConfigNumericEntry;
import io.gitlab.jfronny.respackopts.data.enums.NumericEntryType;
import java.lang.reflect.Type;
public class NumericEntrySerializer implements JsonSerializer<ConfigNumericEntry>, JsonDeserializer<ConfigNumericEntry> {
@Override
public JsonElement serialize(ConfigNumericEntry src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getValue());
}
@Override
public ConfigNumericEntry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) {
ConfigNumericEntry result = new ConfigNumericEntry(NumericEntryType.Box);
result.setValue(json.getAsDouble());
result.setDefault(json.getAsDouble());
return result;
}
else if (json.isJsonObject()) {
JsonObject o = json.getAsJsonObject();
boolean slider = o.has("type") && o.get("type").getAsString().equals("slider");
ConfigNumericEntry result = new ConfigNumericEntry(slider ? NumericEntryType.Slider : NumericEntryType.Box);
JsonElement min = o.get("min");
JsonElement max = o.get("max");
if (slider && (min == null || max == null))
throw new JsonSyntaxException("min/max must not be null for slider");
if (min != null) {
if (min.isJsonPrimitive() && min.getAsJsonPrimitive().isNumber()) {
result.min = min.getAsNumber().doubleValue();
}
else throw new JsonSyntaxException("Expected number as min of numeric entry");
}
if (max != null) {
if (max.isJsonPrimitive() && max.getAsJsonPrimitive().isNumber()) {
result.max = max.getAsNumber().doubleValue();
}
else throw new JsonSyntaxException("Expected number as max of numeric entry");
}
if (slider && (!isWhole(result.min) || !isWhole(result.max)))
throw new JsonSyntaxException("Expected whole number in slider definition");
return result;
}
throw new JsonSyntaxException("Could not deserialize numeric entry");
}
public static boolean isWhole(double v) {
return v == Math.floor(v) && !Double.isInfinite(v);
}
}