summaryrefslogtreecommitdiff
path: root/src/data/ValidatingJsonDeserializer.java
blob: 91c17097aac77d5cd15fae1a9087fea6984240a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package data;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * JSON deserializer which validates that all fields are present.
 *
 * @author Peter Wu.
 */
public class ValidatingJsonDeserializer<T> implements JsonDeserializer<T> {

    @Override
    public T deserialize(JsonElement je, Type type,
            JsonDeserializationContext jdc) throws JsonParseException {
        T obj = new Gson().fromJson(je, type);
        JsonObject jsonObj = je.getAsJsonObject();
        for (Field f : obj.getClass().getDeclaredFields()) {
            if (!jsonObj.has(f.getName())) {
                if (f.getAnnotation(Nullable.class) != null) {
                    // null allowed, skip
                    continue;
                }
                throw new JsonParseException("Missing field: " + f.getName());
            }
            // TODO: validate type?
        }
        return obj;
    }

    public static GsonBuilder addValidation(GsonBuilder gson, Type type) {
        GsonBuilder gb = new GsonBuilder();
        gson.registerTypeAdapter(type, new ValidatingJsonDeserializer());
        for (Field f : type.getClass().getDeclaredFields()) {
            Validator v = f.getAnnotation(Validator.class);
            if (v != null) {
                addValidation(gson, v.deserializer());
            }
        }
        return gb;
    }

    /**
     * Marks a member as object that should be validated too.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface Validator {

        Class deserializer() default ValidatingJsonDeserializer.class;
    }

    /**
     * Marks a member as nullable, that is, it can be missing from the JSON
     * object.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface Nullable {
    }
}