Skip to content

Instantly share code, notes, and snippets.

@adavis
Created October 28, 2014 18:30
Show Gist options
  • Save adavis/4c748e7d7f172b1ae8d9 to your computer and use it in GitHub Desktop.
Save adavis/4c748e7d7f172b1ae8d9 to your computer and use it in GitHub Desktop.
Custom Gson Deserialization
public class CarVO implements Serializable {
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface SkipThis {
// Field tag only annotation
}
private static final long serialVersionUID = 1824858721250363381L;
@SkipThis
private List<SeatVO> seats;
private String name;
private String description;
public CarVO() {}
public void setSeats(List<SeatVO> seats) {
this.seats = seats;
}
public List<SeatVO> getSeats() {
return this.seats;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
/**
* Custom Gson Deserializer to exclude seats that have no buckles
*
* @return Gson
*/
private Gson getGson() {
GsonBuilder b = new GsonBuilder();
b.setExclusionStrategies(new SkipThisAnnotationExclusionStrategy());
b.registerTypeAdapter(CarVO.class, new JsonDeserializer<CarVO>() {
@Override
public CarVO deserialize(JsonElement json, Type arg1,
JsonDeserializationContext arg2) throws JsonParseException {
JsonObject carsJSON = json.getAsJsonObject();
JsonArray seatsJSON = carsJSON.getAsJsonArray("seats");
Gson g = new Gson();
CarVO carVO = g.fromJson(json, CarVO.class);
List<SeatVO> res = new ArrayList<SeatVO>();
for (JsonElement elem : seatsJSON) {
JsonArray bucklesJSON = elem.getAsJsonObject().getAsJsonArray("buckles");
if (!bucklesJSON.isJsonNull() && bucklesJSON.size() > 0) {
res.add(g.fromJson(elem, SeatVO.class));
}
}
carVO.setSeats(res);
return carVO;
}
});
return b.create();
}
private static class SkipThisAnnotationExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> clazz) {
return clazz.getAnnotation(CarVO.SkipThis.class) != null;
}
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(CarVO.SkipThis.class) != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment