theAnonymous
theAnonymous

Reputation: 1804

How to Replace SerializedName

Assuming the JSON i want is {"grrrr":"zzzzz"}

class MyClass{
    @SerializedName("grrrr")
    private String myString;
}

The above class is fine.

However:

class MyClass{
    @MyAnnotation("grrrr")
    private String myString;
}

This would produce {"myString":"zzzzz"}

How to make Gson recognise MyAnnotation#value() and process as SerializedName#value()?

Upvotes: 1

Views: 362

Answers (1)

Andreas
Andreas

Reputation: 159114

To make Gson recognize a home-made annotation, implement a custom FieldNamingStrategy.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MyAnnotation {
    String value();
}
class MyNamingStrategy implements FieldNamingStrategy {
    @Override
    public String translateName(Field f) {
        MyAnnotation annotation = f.getAnnotation(MyAnnotation.class);
        if (annotation != null)
            return annotation.value();
        // Use a built-in policy when annotation is missing, e.g.
        return FieldNamingPolicy.IDENTITY.translateName(f);
    }
}

You then specify it when creating the Gson object.

Gson gson = new GsonBuilder()
        .setFieldNamingStrategy(new MyNamingStrategy())
        .create();

And use it like in the question.

class MyClass{
    @MyAnnotation("grrrr")
    private String myString;
}

Note that @SerializedName overrides any defined strategy, so if you specify both @SerializedName and @MyAnnotation, the @SerializedName value will be used.

Upvotes: 2

Related Questions