Swapnil
Swapnil

Reputation: 2051

Specifying serialized names in java class for firestore document

I am trying to store a document in firestore in my android app using a custom object. If I am using proguard for building my app, is there a way to specify the serialized name for the fields inside my class like the way Gson provides using @SerializedName annotation?

Upvotes: 9

Views: 3015

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599581

You can specify the name a Java property gets in the JSON of the document with the PropertyName annotation. For example:

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

If you use getters and setters (instead of using a public field as above), be sure to put the annotation on both getter and 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; }
}

This annotation is shared between Cloud Firestore and the older Firebase Realtime Database, so I recommend also checking out some of the previous questions about PropertyName, such as Naming convention with Firebase serialization/deserialization?.

Upvotes: 23

Related Questions