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?
            Asked
            
        
        
            Active
            
        
            Viewed 2,704 times
        
    9
            
            
        
        Swapnil
        
- 1,870
 - 2
 - 23
 - 48
 
1 Answers
22
            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?.
        Edric
        
- 24,639
 - 13
 - 81
 - 91
 
        Frank van Puffelen
        
- 565,676
 - 79
 - 828
 - 807
 
- 
                    What if I need the same functionality when saving data into firestore. My field name in java is called `xyzSomethings`. But I want it to be saved as `somethings`. Is there a way? – pvpkiran Apr 20 '20 at 09:31
 - 
                    The exact same annotation exists for Firestore: https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/PropertyName – Frank van Puffelen Apr 20 '20 at 15:15
 - 
                    Thanks for the reply. I tried this. This doesn't work. It works when reading value from firestore. not when saving data into firestore – pvpkiran Apr 20 '20 at 15:44
 - 
                    In that case, please open a new question with the [minimal, complete/standalone code with which anyone can reproduce the problem](http://stackoverflow.com/help/mcve). – Frank van Puffelen Apr 20 '20 at 15:52
 - 
                    1The issue is `@PropertyName` on provate fields doesn't work. It works when putting the annotation on public getters and setters. This question has some info on it https://stackoverflow.com/questions/38681260/firebase-propertyname-doesnt-work. Thanks – pvpkiran Apr 20 '20 at 18:27