在 java class 中为 firestore 文档指定序列化名称

Specifying serialized names in java class for firestore document

我正在尝试使用 custom object 在我的 android 应用程序的 firestore 中存储 document。如果我使用 proguard 来构建我的应用程序,是否有一种方法可以像 Gson 使用 @SerializedName 注释提供的那样为我的 class 中的字段指定序列化名称?

您可以使用 PropertyName 注释指定 Java 属性 在文档的 JSON 中获取的名称。例如:

public class Data {
    @PropertyName("some_field_name")
    public String someFieldName;
}

如果您使用 getters 和 setters(而不是像上面那样使用 public 字段),请务必在 getter 和setter:

public class Data {
    private String someFieldName;

    @PropertyName("some_field_name")
    public String getSomeFieldName() { return someFieldName; }

    @PropertyName("some_field_name")
    public void setSomeFieldName(String someFieldName) { this.someFieldName = someFieldName; }
}

此注释在 Cloud Firestore 和较旧的 Firebase 实时数据库之间共享,因此我建议您也查看一些 previous questions about PropertyName, such as Naming convention with Firebase serialization/deserialization?