Search code examples
parsingkotlinentityandroid-roomdata-persistence

ROOM Entity api field name starts with number


I have an API that returns an object that starts with a number, so I cannot parse it correctly with Room in Kotlin.

@Entity(tableName = "1d")
data class 1D(
        @SerializedName("percent")
        val percent: Double?
)

Data received:

"1d":
{"percent":"22.0"}

Is there a way to make this work?


Solution

  • As you probably know Java and Kotlin cannot handle variable names that begin with a digit. The problem comes from the fact that it will result in things like:

    int 12 = 14 // ????
    

    or

    int 7f = 8 // again 7 float is 8...
    

    Since you are using an API I'm guessing that you are getting a JSON data. What I suggest is that you traverse the data and scan it for these kinds of problem. If you encounter on adding a unique prefix to it and only then save. If you later need to serialize the data back to the API do the same again while removing the prefix every time you encounter one.