Skip to content

Instantly share code, notes, and snippets.

@ashutoshraina
Last active June 2, 2016 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashutoshraina/42a15d707da0708004faec6a7d75eec4 to your computer and use it in GitHub Desktop.
Save ashutoshraina/42a15d707da0708004faec6a7d75eec4 to your computer and use it in GitHub Desktop.
RequiredKeyAdapterFactory.java
public class RequiredKeyAdapterFactory implements TypeAdapterFactory {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type){
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
if (value != null) {
Field[] fields = value.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].isAnnotationPresent(Required.class)) {
validateNullValue(value, fields[i]);
}
}
}
delegate.write(out, value);
}
private <T> void validateNullValue(T value, Field field) {
field.setAccessible(true);
Class t = field.getType();
Object v = null;
try {
v = field.get(value);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
// Put your exhastive if checks here
if (!t.isPrimitive() && v == null) {
throw new JsonParseException(field + " is null");
}
}
@Override
public T read(JsonReader in) throws IOException {
T value = delegate.read(in);
if (value != null) {
Field[] fields = value.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].isAnnotationPresent(Required.class)) {
validateNullValue(value, fields[i]);
}
}
}
return value;
}
};
}
}
@ashutoshraina
Copy link
Author

Usage

  Gson gson = new GsonBuilder()
                    .registerTypeAdapterFactory(new RequiredKeyAdapterFactory())
                    .create();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment