Respackopts/src/main/java/io/gitlab/jfronny/respackopts/gson/entry/NumericEntrySerializer.java
JFronny b3e8cc22cf
All checks were successful
ci/woodpecker/push/docs Pipeline was successful
ci/woodpecker/push/jfmod Pipeline was successful
feat: add support for whole numbers
2023-08-22 12:50:11 +02:00

43 lines
1.9 KiB
Java

package io.gitlab.jfronny.respackopts.gson.entry;
import io.gitlab.jfronny.gson.*;
import io.gitlab.jfronny.respackopts.model.tree.ConfigNumericEntry;
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();
result.setValue(json.getAsDouble());
result.setDefault(json.getAsDouble());
return result;
}
else if (json.isJsonObject()) {
JsonObject o = json.getAsJsonObject();
ConfigNumericEntry result = new ConfigNumericEntry();
JsonElement min = o.get("min");
JsonElement max = o.get("max");
if (min != null) {
if (min.isJsonPrimitive() && min.getAsJsonPrimitive().isNumber()) {
result.setMin(min.getAsNumber().doubleValue());
}
else throw new JsonSyntaxException("Expected number as min of numeric entry");
}
if (max != null) {
if (max.isJsonPrimitive() && max.getAsJsonPrimitive().isNumber()) {
result.setMax(max.getAsNumber().doubleValue());
}
else throw new JsonSyntaxException("Expected number as max of numeric entry");
}
return result;
}
throw new JsonSyntaxException("Could not deserialize numeric entry");
}
}