Deserialize a Firebase Data-Snapshot to a Kotlin data class

蹲街弑〆低调 提交于 2019-11-29 05:02:10

Firebase needs an empty constructor to be able to deserialize the objects:

data class User(
        @Exclude val gUser: Boolean,
        @Exclude val uid: String,
        @PropertyName("display_name") val displayName: String,
        @PropertyName("email") val email: String,
        @PropertyName("account_picture_url") val accountPicUrl: String,
        @PropertyName("provider") val provider: String
) {
    constructor() : this(false, "", "", "", "", "")
}

You can either declare it like so and provide some default values to be able to call the primary constructor or you can declare default values for all your parameters:

data class User (
        @Exclude val gUser: Boolean = false,
        @Exclude val uid: String = "",
        @PropertyName("display_name") val displayName: String = "",
        @PropertyName("email") val email: String = "",
        @PropertyName("account_picture_url") val accountPicUrl: String = "",
        @PropertyName("provider") val provider: String = ""
)

Then various constructors will be created for you, including an empty constructor.

If there's a problem with serialization there might be because of the getters and setters generated by the ide, try reinforcing them with @get and @set annotations:

data class User (
        @Exclude val gUser: Boolean = false,
        @Exclude val uid: String = "",
        @set:PropertyName("display_name") 
        @get:PropertyName("display_name")
        var displayName: String = "",
        @PropertyName("email") val email: String = "",
        @set:PropertyName("account_picture_url")
        @get:PropertyName("account_picture_url")
        var accountPicUrl: String = "",
        @PropertyName("provider") val provider: String = ""
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!