【问题标题】:Why are field annotated with serialized names?为什么用序列化名称注释字段?
【发布时间】:2018-12-11 21:13:17
【问题描述】:

在分页codelab中有这段代码:

/**
 * Immutable model class for a Github repo that holds all the information about a repository.
 * Objects of this type are received from the Github API, therefore all the fields are annotated
 * with the serialized name.
 * This class also defines the Room repos table, where the repo [id] is the primary key.
 */
@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?
)

为什么需要所有这些注释?他们是做什么的?

【问题讨论】:

  • 我的意思是……你看过代码注释了吗……?

标签: android serialization


【解决方案1】:

想象一下这个数据库记录:

id: 21434366,
name: "John",
full_name: "John Doe",
number_of_github_repository: 4

每个字段的键都是小写,下划线分隔的格式。但是,字段/变量的一般命名约定基于驼峰式大小写。

而不是使用字段名本身作为变量名

val number_of_github_repository: Int 

我们都喜欢这个

val numOfGithubRepos: Int

这就是@field:SerializedName 注释发挥作用的地方。如果您使用实际的数据库字段名称注释变量名称,程序将从注释名称中找到值并将其分配给您自定义的变量名称。

例如,

@field:SerializedName("number_of_github_repositories") val numOfGithubRepos: Int 

这将从您的数据库字段“number_of_github_repositories”中查找值并将其分配给变量 numOfGithubRepos。

GSON 库也是如此。它将不需要的/无组织的字段名称转换为您喜欢的变量名称。默认情况下,GSON 库尝试从 Json 响应中查找与声明的变量名称匹配的字段。所以如果你只是声明了没有注解的字段,像这样,

val numOfGithubRepos: Int 

如果实际的 Json 对象是

{num_of_github_repositories: 4}

它将引发异常,因为 Json 响应中没有名称为 numOfGithubRepos 的此类字段。

【讨论】:

    【解决方案2】:

    它们来自 json 形式的 api。 json 有一个键值结构,其中有名称和值,因此注释指示您要查找的键,然后返回值,在本例中为长字符串和整数。我希望我足够清楚。 =)

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多