From 987427b8938e1294466541b1a9cc274098550082 Mon Sep 17 00:00:00 2001 From: mcrcortex <18544518+MCRcortex@users.noreply.github.com> Date: Fri, 25 Apr 2025 12:15:50 +1000 Subject: [PATCH] multi gson --- .../me/cortex/voxy/common/util/MultiGson.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/main/java/me/cortex/voxy/common/util/MultiGson.java diff --git a/src/main/java/me/cortex/voxy/common/util/MultiGson.java b/src/main/java/me/cortex/voxy/common/util/MultiGson.java new file mode 100644 index 00000000..a811092f --- /dev/null +++ b/src/main/java/me/cortex/voxy/common/util/MultiGson.java @@ -0,0 +1,72 @@ +package me.cortex.voxy.common.util; + +import com.google.gson.*; + +import java.lang.reflect.Modifier; +import java.util.*; + +public class MultiGson { + private final List> classes; + private final Gson GSON = new GsonBuilder() + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .setPrettyPrinting() + .excludeFieldsWithModifiers(Modifier.PRIVATE) + .create(); + + private MultiGson(List> classes) { + this.classes = classes; + } + + public String toJson(Object... objects) { + Object[] map = new Object[this.classes.size()]; + if (map.length != objects.length) { + throw new IllegalArgumentException("Incorrect number of input args"); + } + for (var obj : objects) { + if (obj == null) { + throw new IllegalArgumentException(); + } + int i = this.classes.indexOf(obj.getClass()); + if (i == -1) { + throw new IllegalArgumentException("Unknown object class: " + obj.getClass()); + } + if (map[i] != null) { + throw new IllegalArgumentException("Duplicate entry classes"); + } + } + + var json = new JsonObject(); + for (Object entry : map) { + GSON.toJsonTree(entry).getAsJsonObject().asMap().forEach((i,j) -> { + if (json.has(i)) { + throw new IllegalArgumentException("Duplicate name inside unified json: " + i); + } + json.add(i, j); + }); + } + return GSON.toJson(json); + } + + public Map, Object> fromJson(String json) { + var obj = GSON.fromJson(json, JsonObject.class); + LinkedHashMap, Object> objects = new LinkedHashMap<>(); + for (var cls : this.classes) { + objects.put(cls, GSON.fromJson(obj, cls)); + } + return objects; + } + + public static class Builder { + private final LinkedHashSet> classes = new LinkedHashSet<>(); + public Builder add(Class clz) { + if (!this.classes.add(clz)) { + throw new IllegalArgumentException("Class has already been added"); + } + return this; + } + + public MultiGson build() { + return new MultiGson(new ArrayList<>(this.classes)); + } + } +}