Ignore case for keys and fix types when deserializing

This commit is contained in:
Sollace 2019-05-30 22:03:37 +02:00
parent f29b4af99d
commit 329e02ec56
2 changed files with 13 additions and 9 deletions

View file

@ -17,7 +17,7 @@ public abstract class Config {
protected void initWith(Setting<?>... settings) {
for (Setting<?> s : settings) {
entries.putIfAbsent(s.name(), s.getDefault());
entries.putIfAbsent(s.name().toLowerCase(), s.getDefault());
}
}
@ -34,7 +34,7 @@ public abstract class Config {
this.name = name;
this.def = def;
entries.putIfAbsent(name(), def);
entries.putIfAbsent(name().toLowerCase(), def);
}
@Override
@ -76,7 +76,7 @@ public abstract class Config {
@Nonnull
@SuppressWarnings("unchecked")
default T get() {
T t = (T)config().entries.computeIfAbsent(name(), k -> getDefault());
T t = (T)config().entries.computeIfAbsent(name().toLowerCase(), k -> getDefault());
if (t == null) {
t = getDefault();
@ -92,7 +92,7 @@ public abstract class Config {
*/
default void set(@Nullable T value) {
value = value == null ? getDefault() : value;
config().entries.put(name(), value);
config().entries.put(name().toLowerCase(), value);
}
@Override

View file

@ -2,6 +2,7 @@ package com.minelittlepony.settings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.stream.JsonWriter;
import java.io.BufferedReader;
@ -9,7 +10,6 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class JsonConfig extends Config {
@ -41,11 +41,15 @@ public class JsonConfig extends Config {
try {
if (Files.exists(file)) {
try (BufferedReader s = Files.newBufferedReader(file)) {
Map<String, Object> parsed = gson.fromJson(s, HashMap.class);
gson.fromJson(s, JsonObject.class).entrySet().forEach(entry -> {
String key = entry.getKey().toLowerCase();
if (parsed != null) {
entries = parsed;
}
if (entries.containsKey(key)) {
Object value = gson.getAdapter(entries.get(key).getClass()).fromJsonTree(entry.getValue());
entries.put(key, value);
}
});
} catch (IOException ignored) { }
}
configFile = file;