Archive for the ‘gson’ tag
Skipping Fields when deserializing JSON using gson
Recently, we’re working on legacy code, where a json strings were to be serialized into java classes. These java classes had a deep hierarchy and some classes had field names same as defined in their parent classes. And these fields were not used at all.
GSON, makes it very simple to handle such scenarios. Use GsonBuilder and add an exclusionStrategy.
E.g.:
[code lang=”java”]
new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes field) {
if (field.getName().equals(“FIELD_NAME_TO_BE_SKIPED”)) {
return true;
}
return false;
}
@Override
public boolean shouldSkipClass(Class> clazz) {
return clazz.equals(CLASS_TO_BE_SKIPPED.class);
}
}).create().fromJson(json, respClass);
[/code]