From 9be617801a8dabe4bcae017c2f671c5c10b3aebb Mon Sep 17 00:00:00 2001 From: Peter Wu Date: Fri, 9 May 2014 15:14:23 +0200 Subject: Trace object path for JSON validation errors. --- src/data/ValidatingJsonDeserializer.java | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) (limited to 'src/data/ValidatingJsonDeserializer.java') 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 implements JsonDeserializer { 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 implements JsonDeserializer { // 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 implements JsonDeserializer { 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); } } } -- cgit v1.2.1