From 651e477d0da9f74f3e2193de6827c9ff9d098564 Mon Sep 17 00:00:00 2001 From: Peter Wu Date: Sat, 10 May 2014 10:41:33 +0200 Subject: Verify that an array and object are really array (and objects) --- src/data/ValidatingJsonDeserializer.java | 12 +++++++----- test/data/ValidatingJsonDeserializerTest.java | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/data/ValidatingJsonDeserializer.java b/src/data/ValidatingJsonDeserializer.java index 1474de3..5dca3bd 100644 --- a/src/data/ValidatingJsonDeserializer.java +++ b/src/data/ValidatingJsonDeserializer.java @@ -55,24 +55,26 @@ public class ValidatingJsonDeserializer implements JsonDeserializer { private void tryValidateProperty(String path, JsonElement je, Field f) { // assume that this annotation is only applied to objects Validator v = f.getAnnotation(Validator.class); + path += f.getName(); if (v != null) { Class type = f.getType(); if (type.isArray()) { // the class expects an array, so the value must have one too. if (!je.isJsonArray()) { - throw new JsonParseException("Not an array: " + path + f.getName()); + throw new JsonParseException("Expected array: " + path); } 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(path, arr_je, type); + checkObject(path + ".", arr_je, type); } } else { // not an array, assume a verifiable object - path += f.getName() + "."; // e.g. foo - checkObject(path, je, type); + if (!je.isJsonObject()) { + throw new JsonParseException("Expected object: " + path); + } + checkObject(path + ".", je, type); } } } diff --git a/test/data/ValidatingJsonDeserializerTest.java b/test/data/ValidatingJsonDeserializerTest.java index a8b1955..85f1661 100644 --- a/test/data/ValidatingJsonDeserializerTest.java +++ b/test/data/ValidatingJsonDeserializerTest.java @@ -543,6 +543,20 @@ public class ValidatingJsonDeserializerTest { checkTweetFail(tweet, "Expected string: text"); } + @Test + public void testWrongTypeArray() { + JsonObject tweet = buildMinimalTweet(buildMinimalUser()); + addProperty(tweet, new JsonPrimitive(1), "entities", "urls"); + checkTweetFail(tweet, "Expected array: entities.urls"); + } + + @Test + public void testWrongTypeObject() { + JsonObject tweet = buildMinimalTweet(buildMinimalUser()); + addProperty(tweet, new JsonPrimitive(1), "entities"); + checkTweetFail(tweet, "Expected object: entities"); + } + @Test public void testNotATweetObject() { try { -- cgit v1.2.1