Why does the author add @field:SerializedName annotation to a field in Room database?

Viewed 1241

I'm learning Room with a sample code at https://github.com/googlecodelabs/android-paging

The Code A is to defind a @Entity of a table, you can see it.

Normally it add the @ColumnInfo annotation to a field, such as @ColumnInfo(name = "first_name") val firstName: String?, ... .

Why does the author add @field:SerializedName annotation to a field in Room database?

Code A

@Entity(tableName = "repos")
data class Repo(
    @PrimaryKey @field:SerializedName("id") val id: Long,
    @field:SerializedName("name") val name: String,
    @field:SerializedName("full_name") val fullName: String,
    @field:SerializedName("description") val description: String?,
    @field:SerializedName("html_url") val url: String,
    @field:SerializedName("stargazers_count") val stars: Int,
    @field:SerializedName("forks_count") val forks: Int,
    @field:SerializedName("language") val language: String?
)
1 Answers

The @SerializedName annotation is part of Gson and is used to define the names of these properties in Json.

The @ColumnInfo annotation is part of Room and is used to define the column names of these properties in SQLite.

If neither of these annotation is defined, the property/field name is used as a name for the Json property or column.

Why does the author add @field:SerializedName annotation to a field in Room database?

Because the Room entity is reused as a Gson DTO.

Related