简体   繁体   中英

How to use multiple Java annotations with the same value?

I'm using Retrofit along with GSON to retrieve data from an API and deserialize it to Java objects using GSON's @SerializedName annotation like below:

public class MyApiObject {
    @SerializedName("apiJsonKey")
    private String myValue;
    ...
}

It works fine, but I need to send objects of MyApiObject to a Firebase database and for that the object needs to be serialized back to JSON. Firebase's Java API does this automatically, but it generates the keys based on the instance variable's names ( myValue ) and not the serialized name ( "apiJsonKey" ).

I know I can use Firebase's @PropertyName annotation, but that would require me to use two annotations with the same values, which is redundant and error-prone.

Is there a better way to do this?

The usual aproach in this cases is to set a constant and use it in both annotations.

public class MyApiObject {
    private static final String MY_VALUE_NAME = "apiJsonKey";

    @SerializedName(MY_VALUE_NAME)
    @ParameterName(MY_VALUE_NAME)
    private String myValue;
    ...
}

This is fairly usual in sequence annotations for JPA.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM