summaryrefslogtreecommitdiff
path: root/src/data/ValidatingJsonDeserializer.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/data/ValidatingJsonDeserializer.java')
-rw-r--r--src/data/ValidatingJsonDeserializer.java22
1 files changed, 17 insertions, 5 deletions
diff --git a/src/data/ValidatingJsonDeserializer.java b/src/data/ValidatingJsonDeserializer.java
index d5a8dbc..6fd9dc7 100644
--- a/src/data/ValidatingJsonDeserializer.java
+++ b/src/data/ValidatingJsonDeserializer.java
@@ -21,12 +21,22 @@ import java.lang.reflect.Type;
*/
public class ValidatingJsonDeserializer<T> implements JsonDeserializer<T> {
+ private final Gson gson;
+
+ public ValidatingJsonDeserializer() {
+ this(new Gson());
+ }
+
+ public ValidatingJsonDeserializer(Gson gson) {
+ this.gson = gson;
+ }
+
@Override
public T deserialize(JsonElement je, Type type,
JsonDeserializationContext jdc) throws JsonParseException {
T obj;
try {
- obj = new Gson().fromJson(je, type);
+ obj = gson.fromJson(je, type);
} catch (JsonParseException jpe) {
DebuggingJsonDeserializer.tryValidate(je.toString(), (Class) type);
throw new JsonParseException("Debugger could not find a bug", jpe);
@@ -35,7 +45,7 @@ public class ValidatingJsonDeserializer<T> implements JsonDeserializer<T> {
return obj;
}
- void checkObject(String path, JsonElement je, Class type)
+ protected final void checkObject(String path, JsonElement je, Class type)
throws JsonParseException {
JsonObject jsonObj = je.getAsJsonObject();
for (Field f : type.getDeclaredFields()) {
@@ -53,15 +63,14 @@ public class ValidatingJsonDeserializer<T> implements JsonDeserializer<T> {
}
}
tryValidateProperty(path, val, f);
- // TODO: validate type?
}
}
private void tryValidateProperty(String path, JsonElement je, Field f)
throws JsonParseException {
Class<?> type = f.getType();
- // assume that this annotation is only applied to objects
- Validator v = f.getAnnotation(Validator.class);
+
+ // validates arrays
ArrayValidator av = f.getAnnotation(ArrayValidator.class);
path += f.getName();
if (av != null) {
@@ -83,6 +92,9 @@ public class ValidatingJsonDeserializer<T> implements JsonDeserializer<T> {
+ maxLen + ": " + path);
}
}
+
+ // validates objects, recursively
+ Validator v = f.getAnnotation(Validator.class);
if (v != null) {
if (type.isArray()) {
// the class expects an array, so the value must have one too.