'Kotlin: Json: conflicting annotation schemes for name transcription
I read data from Firebase database into a Kotlin/Android program. The key names in Firebase are different from those of the corresponding Kotlin variables. I test this code with flat JSON files (for good reasons) where I retain the same key names used in Firebase, so I need to transcribe them too.
Firebase wants to annotate variables with @PropertyName; but Gson, which I use to read flat files, wants @SerializedName (which Firebase doesn't understand, unfortunately.)
Through trial and error I found that this happens to work:
@SerializedName("seq")
var id: Int? = null
@PropertyName("seq")
get
@PropertyName("seq")
set
Both Firebase and Gson do their thing and my class gets its data. Am I hanging by a thin thread here? Is there a better way to do this?
Thank you!,
Solution 1:[1]
You can probably solve this by using Kotlin's @JvmField to suppress generation of getters and setters. This should allow you to place the @PropertyName annotation directly on the property. You can then implement a Gson FieldNamingStrategy which checks if a @PropertyName annotation is present on the field and in that case uses its value; otherwise it could return the field name. The FieldNamingStrategy has to be set on a GsonBuilder which you then use to create the Gson instance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcono1234 |
