THE STORY
I am using Firebase Realtime Database in my app. I have a model something like this.
class Item {
int mItemName;
/
Finally got a chance to solve this problem. Thanks to @hatboysam for the suggestion.
The only problem was, @PropertyName
annotation was not properly documented in Firebase.
The first thing that is necessary is the the field must be public otherwise the annotation will not work, which is quite obvious/
Now the annotation takes into account both the field name as well as the getter/setter names to serialize. I also had the problem where the fields as well as the getter/setters were getting serialized, resulting in duplicate key/value pairs.
I solved the problem by using the annotation on the field name which were public and ignoring the getter/setters. This solved the problem perfectly. Not the data was properly serialized with the property name I wanted and there was no duplicate data problem as well.
Here is a simple example,
class Item {
@PropertyName("item_no")
int mItemNo;
// Simplified for brevity
@Exclude
public int getItemNo(){
return mItemNo;
}
@Exclude
public void setItemNo(int itemNo){
this.mItemNo = itemNo;
}
}
Solution for Kotlin data class:
data class Pojo (@get:PropertyName("fieldName") @set:PropertyName("fieldName") var field: String = "")
Alternatively just mark your getters with @PropertyName
instead of annotating properties themselves - this way you can keep properties private while providing custom names:
public class User extends Object {
private String mDisplayName;
@PropertyName("userName")
public String getDisplayName() {
return mDisplayName;
}
@PropertyName("userName")
public void setDisplayName(String displayName) {
mDisplayName = displayName;
}
}