private <T> List<T> deserializeAsArray( JsonElement json, JsonDeserializationContext context, TypeToken<T> typeToken, Type listOfT) { if (json.isJsonPrimitive()) { List<T> list = new ArrayList<T>(); list.add((T) context.deserialize(json, typeToken.getType())); return list; } else { return context.deserialize(json, listOfT); } }
@Override public Segment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.getAsJsonObject().has("class")) { throw new ProtectionParseException("One of the segments is missing a class identifier"); } JsonObject jsonObject = json.getAsJsonObject(); String classString = jsonObject.get("class").getAsString(); if (!json.getAsJsonObject().has("type")) { throw new ProtectionParseException("Segment for " + classString + " is missing a type"); } String type = jsonObject.get("type").getAsString(); jsonObject.remove("type"); Segment segment = null; if ("specialBlock".equals(type)) { segment = deserializeSpecialBlock(jsonObject, context); } else if ("block".equals(type)) { segment = deserializeBlock(jsonObject, context); } else if ("entity".equals(type)) { segment = deserializeEntity(jsonObject, context); } else if ("item".equals(type)) { segment = deserializeItem(jsonObject, context); } else if ("tileEntity".equals(type)) { segment = deserializeTileEntity(jsonObject, context); } if (segment == null) { throw new ProtectionParseException("Identifier type is invalid"); } try { segment.checkClass = Class.forName(classString); } catch (ClassNotFoundException ex) { // throw new ProtectionParseException("Invalid class identifier: " + classString); MyTown.instance.LOG.error( "Invalid class identifier {" + classString + "}: >>> Segment Rejected <<<"); return null; } jsonObject.remove("class"); if (!(segment instanceof SegmentSpecialBlock)) { if (!json.getAsJsonObject().has("flags")) { throw new ProtectionParseException("Segment for " + classString + " is missing flags"); } segment.flags.addAll( deserializeAsArray( jsonObject.get("flags"), context, new TypeToken<FlagType<Boolean>>() {}, new TypeToken<List<FlagType<Boolean>>>() {}.getType())); jsonObject.remove("flags"); if (jsonObject.has("condition")) { segment.condition = new Condition(jsonObject.get("condition").getAsString()); jsonObject.remove("condition"); } if (jsonObject.has("priority")) { segment.priority = Priority.valueOf(jsonObject.get("priority").getAsString()); jsonObject.remove("priority"); } for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { Getter getter = context.deserialize(entry.getValue(), Getter.class); getter.setName(entry.getKey()); segment.getters.add(getter); } } return segment; }