How do I use multiple Java annotations with the same meaning?

I am using Retrofit along with GSON to fetch data from an API and deserialize it to Java objects using GSON annotation @SerializedName

as shown below:

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

      

It works great, but I need to send objects MyApiObject

to Firebase database and for that the object needs to be serialized back to JSON. The Firebase Java API does this automatically, but generates keys based on the instance variable names ( myValue

), not the serialized name ( "apiJsonKey"

).

I know I can use Firebase annotation @PropertyName

, but that would require me to use two annotations with the same values, which are redundant and error prone.

Is there a better way to do this?

+3


source to share


1 answer


The usual aproach in this case 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 a fairly common sequence in JPA annotations.

+2


source







All Articles