Adding a custom TypeAdapterFactory for Google GSON to detect use of annotations to return custom TypeAdapter dynamically Adding a custom TypeAdapterFactory for Google GSON to detect use of annotations to return custom TypeAdapter dynamically json json

Adding a custom TypeAdapterFactory for Google GSON to detect use of annotations to return custom TypeAdapter dynamically


How about using @JsonAdapter? You anyway need to know how to do de-/crypting and need to implement tha per type. For string in your case, for example:

public class CryptoAdapter extends TypeAdapter<String> {    @Override    public void write(JsonWriter out, String value) throws IOException {        out.jsonValue(org.apache.commons.lang3.StringUtils.reverse(value));    }    @Override    public String read(JsonReader in) throws IOException {        return org.apache.commons.lang3.StringUtils.reverse(in.nextString());    }}

Usage:

public class Test {    @JsonAdapter(CryptoAdapter.class)    String abc = "def";}

The problem is that Gson does not provide (to my knowledge) any direct means to create some own field processor that lets user to read the field/class member annotations.

In other words you need an access to the field during de-/serialization and that seem not to be possible in an easy way.

That is why there is this @JsonAdapter.

If interested to study more clone source code from GitHub and check:

public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory

Unfortunately final. There is a method named createBoundField (which I think is the logic behind recognizing @JsonAdapter for fields) and the path and overriding that logic is not so straightforward.

For classes there seems to be solution quite similar to yours:

public final class JsonAdapterAnnotationTypeAdapterFactory    implements TypeAdapterFactory

Both above mentioned are added to the list of TypeAdapterFactories when a new Gson is created.