Exception_Prototype

Untitled

Oct 22nd, 2023
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. public enum GsonHelper {
  2.  
  3.         INSTANCE;
  4.  
  5.         public static final Gson GSON = new GsonBuilder()
  6.                 .disableHtmlEscaping()
  7.                 .registerTypeAdapter(Region.class, new RegionAdapter())
  8.                 .create();
  9.  
  10.     }
  11.  
  12.     public interface Region {
  13.  
  14.         String getName();
  15.  
  16.         UUID getUUID();
  17.  
  18.         Chunk getChunk();
  19.  
  20.     }
  21.  
  22.     public class RegionImpl implements Region {
  23.  
  24.  
  25.         private final String name;
  26.         private final UUID uuid;
  27.         private final Chunk chunk;
  28.  
  29.         public RegionImpl(String name, UUID uuid, Chunk chunk) {
  30.             this.name = name;
  31.             this.uuid = uuid;
  32.             this.chunk = chunk;
  33.         }
  34.  
  35.         String toJson() {
  36.             return GsonHelper.GSON.toJson(this, Region.class);
  37.         }
  38.  
  39.         Region fromJson(String json) {
  40.             return GsonHelper.GSON.fromJson(json, Region.class);
  41.         }
  42.  
  43.     }
  44.  
  45.     public static class RegionAdapter implements JsonSerializer<Region>, JsonDeserializer<Region> {
  46.  
  47.         @Override
  48.         public Region deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
  49.             final var object = json.getAsJsonObject();
  50.             String name = object.get("name").getAsString();
  51.             UUID uuid = context.deserialize(object.get("uuid"), UUID.class); // implements custom UUIDAdapter and register
  52.             final String worldName = object.get("worldName").getAsString();
  53.             // problem with getting chunk for creating region
  54.             return new RegionImpl(name, uuid, todo: chunk);
  55.         }
  56.  
  57.         @Override
  58.         public JsonElement serialize(Region src, Type typeOfSrc, JsonSerializationContext context) {
  59.             JsonObject object = new JsonObject();
  60.             object.addProperty("name", src.getName());
  61.             object.add("uuid", context.serialize(src.getUUID(), UUID.class));
  62.             object.addProperty("worldName", src.getChunk().getWorld().getName());
  63.             return object;
  64.         }
  65.  
  66.     }
Add Comment
Please, Sign In to add comment