It looks like I can write adapters to do custom processing (serialize / deserialize) based on object type. It would be really nice to also do custom serialization / deserialization processing based on custom annotations.
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
}
public class SampleEntity {
private String nameField;
@MyCustomAnnotation // <<< THIS IS THE CUSTOM ANNOTATION
private String processField;
public SampleEntity(String f1, String f2) {
nameField = f1;
processField = f2;
}
public String getNameField() {
return nameField;
}
public void setNameField(String nameField) {
this.nameField = nameField;
}
public String getProcessField() {
return processField;
}
public void setProcessField(String processField) {
this.processField = processField;
}
}
// main fragment
{
// create the gson object via the gson builder
GsonBuilder gsonBuilder = new GsonBuilder();
// ====> HERE'S THE NEW PART TO ALLOW PROCESSING CUSTOM ANNOTATIONS ON A FIELD <====
gsonBuilder.registerAnnotationAdapter(MyCustomAnnotation.class, new MyCustomAnnotationAdapter());
gson = gsonBuilder.create();
String json = gson.toJson(new SampleEntity("foo1", "foo2");
System.out.println("my json = " + json);
}
// custom annotation adapter class
public class MyCustomAnnotationAdapter implements JsonSerializer<MyCustomAnnotation>, JsonDeserializer<MyCustomAnnotation> {
// JsonSerializer and JsonDeserializer would need to provide access to the field information for adapter to work
@Override
public JsonElement serialize(SecureId src, Type typeOfSrc, JsonSerializationContext context) {
// todo ...
}
@Override
public SecureId deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
// todo ...
}
}
The idea is to be able to provide custom serialization and deserialization on a field level based on a custom annotation on that field. If this is already possible, it would be great to get a pointer to the documentation or a code snippet.