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.java21
1 files changed, 10 insertions, 11 deletions
diff --git a/src/data/ValidatingJsonDeserializer.java b/src/data/ValidatingJsonDeserializer.java
index e38f68f..511264d 100644
--- a/src/data/ValidatingJsonDeserializer.java
+++ b/src/data/ValidatingJsonDeserializer.java
@@ -26,14 +26,11 @@ public class ValidatingJsonDeserializer<T> implements JsonDeserializer<T> {
public T deserialize(JsonElement je, Type type,
JsonDeserializationContext jdc) throws JsonParseException {
T obj = new Gson().fromJson(je, type);
- checkObject(je, obj.getClass());
+ checkObject("", je, obj.getClass());
return obj;
}
- private void checkObject(JsonElement je, Class type) {
- if (!je.isJsonObject()) {
- throw new JsonParseException("Expected object: " + type.getName());
- }
+ private void checkObject(String path, JsonElement je, Class type) {
JsonObject jsonObj = je.getAsJsonObject();
for (Field f : type.getDeclaredFields()) {
if (!jsonObj.has(f.getName())) {
@@ -41,14 +38,14 @@ public class ValidatingJsonDeserializer<T> implements JsonDeserializer<T> {
// null allowed, skip
continue;
}
- throw new JsonParseException("Missing field: " + f.getName());
+ throw new JsonParseException("Missing field: " + path + f.getName());
}
- tryValidateProperty(jsonObj.get(f.getName()), f);
+ tryValidateProperty(path, jsonObj.get(f.getName()), f);
// TODO: validate type?
}
}
- private void tryValidateProperty(JsonElement je, Field f) {
+ private void tryValidateProperty(String path, JsonElement je, Field f) {
// assume that this annotation is only applied to objects
Validator v = f.getAnnotation(Validator.class);
if (v != null) {
@@ -56,17 +53,19 @@ public class ValidatingJsonDeserializer<T> implements JsonDeserializer<T> {
if (type.isArray()) {
// the class expects an array, so the value must have one too.
if (!je.isJsonArray()) {
- throw new JsonParseException("Not an array: " + f.getName());
+ throw new JsonParseException("Not an array: " + path + f.getName());
}
JsonArray ja = je.getAsJsonArray();
type = type.getComponentType();
// for each array element, check if the object is valid.
+ path += f.getName() + "."; // e.g. foo[]
for (JsonElement arr_je : ja) {
- checkObject(arr_je, type);
+ checkObject(path, arr_je, type);
}
} else {
// not an array, assume a verifiable object
- checkObject(je, type);
+ path += f.getName() + "."; // e.g. foo
+ checkObject(path, je, type);
}
}
}