blob: e0f1a64f353ef15582795faabc6358427f9cbad3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
package eu.olli.cowlection.util;
import com.google.gson.*;
import com.mojang.util.UUIDTypeAdapter;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraftforge.common.util.Constants;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.UUID;
public final class GsonUtils {
private static final Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
private static final Gson gsonPrettyPrinter = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).setPrettyPrinting().create();
private GsonUtils() {
}
public static <T> T fromJson(String json, Type clazz) {
return gson.fromJson(json, clazz);
}
public static <T> T fromJson(Reader json, Class<T> clazz) {
return gson.fromJson(json, clazz);
}
public static String toJson(Object object) {
if (object instanceof NBTBase) {
return gsonPrettyPrinter.toJson(nbtToJson((NBTBase) object));
} else {
return gson.toJson(object);
}
}
private static JsonElement nbtToJson(NBTBase nbtElement) {
if (nbtElement instanceof NBTBase.NBTPrimitive) {
NBTBase.NBTPrimitive nbtNumber = (NBTBase.NBTPrimitive) nbtElement;
switch (nbtNumber.getId()) {
case Constants.NBT.TAG_BYTE:
return new JsonPrimitive(nbtNumber.getByte());
case Constants.NBT.TAG_SHORT:
return new JsonPrimitive(nbtNumber.getShort());
case Constants.NBT.TAG_INT:
return new JsonPrimitive(nbtNumber.getInt());
case Constants.NBT.TAG_LONG:
return new JsonPrimitive(nbtNumber.getLong());
case Constants.NBT.TAG_FLOAT:
return new JsonPrimitive(nbtNumber.getFloat());
case Constants.NBT.TAG_DOUBLE:
return new JsonPrimitive(nbtNumber.getDouble());
default:
return new JsonObject();
}
} else if (nbtElement instanceof NBTTagString) {
return new JsonPrimitive(((NBTTagString) nbtElement).getString());
} else if (nbtElement instanceof NBTTagList) {
NBTTagList nbtList = (NBTTagList) nbtElement;
JsonArray jsonArray = new JsonArray();
for (int tagId = 0; tagId < nbtList.tagCount(); tagId++) {
jsonArray.add(nbtToJson(nbtList.get(tagId)));
}
return jsonArray;
} else if (nbtElement instanceof NBTTagCompound) {
NBTTagCompound nbtCompound = (NBTTagCompound) nbtElement;
JsonObject jsonObject = new JsonObject();
for (String nbtEntry : nbtCompound.getKeySet()) {
jsonObject.add(nbtEntry, nbtToJson(nbtCompound.getTag(nbtEntry)));
}
return jsonObject;
}
return new JsonObject();
}
}
|