summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPeter Wu <peter@lekensteyn.nl>2014-05-10 10:41:33 +0200
committerPeter Wu <peter@lekensteyn.nl>2014-05-10 10:41:33 +0200
commit651e477d0da9f74f3e2193de6827c9ff9d098564 (patch)
tree31bf598605e318ee8d041ad61dff4a721bb6b97e
parent00d14d387bcb5a788195326c6893f729a9ee863d (diff)
downloadDatafiller-651e477d0da9f74f3e2193de6827c9ff9d098564.tar.gz
Verify that an array and object are really array (and objects)
-rw-r--r--src/data/ValidatingJsonDeserializer.java12
-rw-r--r--test/data/ValidatingJsonDeserializerTest.java14
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<T> implements JsonDeserializer<T> {
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
@@ -544,6 +544,20 @@ public class ValidatingJsonDeserializerTest {
}
@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 {
DebuggingJsonDeserializer.tryValidate("{}", Tweet.class);