Firebase @PropertyName doesn't work

后端 未结 3 1653
不知归路
不知归路 2020-11-28 09:22

THE STORY

I am using Firebase Realtime Database in my app. I have a model something like this.

class Item {
    int mItemName;
    /         


        
相关标签:
3条回答
  • 2020-11-28 09:42

    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;
            }
        }
    
    0 讨论(0)
  • 2020-11-28 09:55

    Solution for Kotlin data class:

    data class Pojo (@get:PropertyName("fieldName") @set:PropertyName("fieldName") var field: String = "")
    
    0 讨论(0)
  • 2020-11-28 09:58

    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;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题