Last active
June 2, 2016 13:28
-
-
Save ashutoshraina/42a15d707da0708004faec6a7d75eec4 to your computer and use it in GitHub Desktop.
RequiredKeyAdapterFactory.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage