[英]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: 我正在使用Retrofit和GSON从API检索数据,并使用GSON的
@SerializedName
注释将其反序列化为Java对象,如下所示:
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. 它工作正常,但我需要将
MyApiObject
对象发送到Firebase数据库,并且需要将对象序列化回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"
). Firebase的Java API会自动执行此操作,但它会根据实例变量的名称(
myValue
)生成密钥,而不是序列化名称( "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. 我知道我可以使用Firebase的
@PropertyName
注释,但这需要我使用两个具有相同值的注释,这是多余的,容易出错。
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. 这在JPA的序列注释中是相当常见的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.