2021-10-03 16:45:29 +02:00
|
|
|
package io.gitlab.jfronny.respackopts.gson.entry;
|
|
|
|
|
|
|
|
import com.google.gson.*;
|
2021-11-14 15:37:01 +01:00
|
|
|
import io.gitlab.jfronny.respackopts.model.tree.ConfigNumericEntry;
|
|
|
|
import io.gitlab.jfronny.respackopts.model.enums.NumericEntryType;
|
2021-10-03 16:45:29 +02:00
|
|
|
|
|
|
|
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");
|
|
|
|
}
|
2021-11-14 15:37:01 +01:00
|
|
|
if (slider && (isOdd(result.min) || isOdd(result.max)))
|
2021-10-03 16:45:29 +02:00
|
|
|
throw new JsonSyntaxException("Expected whole number in slider definition");
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
throw new JsonSyntaxException("Could not deserialize numeric entry");
|
|
|
|
}
|
|
|
|
|
2021-11-14 15:37:01 +01:00
|
|
|
public static boolean isOdd(double v) {
|
|
|
|
return v != Math.floor(v) || Double.isInfinite(v);
|
2021-10-03 16:45:29 +02:00
|
|
|
}
|
|
|
|
}
|