【问题标题】:How to access the value of a key inside a key in a JSON response in android fetched with Retrofit2?如何访问使用Retrofit2获取的android中JSON响应中键内键的值?
【发布时间】:2018-09-02 15:52:40
【问题描述】:

我正在访问 WordPress API 以使用 Retrofit2 获取帖子,然后当我尝试将值分配给适配器中的视图时:

inner class MainActivityViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    fun bind(post: Post) {
        with(post) {
            itemView.tv_post_title.text = title
            itemView.tv_post_date.text = date
            itemView.tv_post_content.text = content
        }
    }
}

Retrofit 的 GET 返回一个 Observable,因此,当它尝试分配时,onErrorResumeNext 中会显示以下错误:

java.lang.IllegalStateException: 应为字符串,但在第 1 行第 373 列路径 $[0].title 处为 BEGIN_OBJECT

这是因为title 键中有一个rendered 键:

{  
  id:497,
  date:"2018-04-08T03:34:12",
  [...]
  title:{  
    rendered:"Lorem ipsum dolor sit amet"
  }
}

这同样适用于contentexcerpt。如何访问这些 rendereds 密钥?我尝试了类似的东西

val 标题:JsonElement = JsonParser().parse(post.title)

但同样的错误仍然存​​在。

【问题讨论】:

  • 请添加您的代码。
  • 做了一些改动。

标签: android json retrofit2


【解决方案1】:

发生这种情况是因为 json 解析器无法解析标题对象。

java.lang.IllegalStateException: 应为字符串,但在第 1 行第 373 列路径 $[0].title 处为 BEGIN_OBJECT

为避免此运行时错误,click here to create java pojo for expected json 然后将其用作改造 api 中的返回类型。

尝试对使用上述工具创建的 json 使用以下 java pojo。

Post.kt

data class Post(
    @PrimaryKey(autoGenerate = true)
    @SerializedName("id")
    val id: Int,

    @SerializedName("title")
    @Embedded
    val title: Title,

    @SerializedName("excerpt")
    @Embedded
    val excerpt: Excerpt,

    @SerializedName("content")
    @Embedded
    val content: Content,

    @SerializedName("date")
    val date: String,

    @SerializedName("modified")
    val modified: String
)

内容.kt

class Content {
    @SerializedName("rendered")
    var content: String? = null
}

标题.kt

class Title {
    @SerializedName("rendered")
    var title: String? = null
}

摘录.kt

class Excerpt {
    @SerializedName("rendered")
    var excerpt: String? = null
}

为 Gson 导入以下依赖项

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@SerializedName:提供将 JSON 键映射到与 JSON 键不同名称的 java 成员变量的能力。 Check this question

【讨论】:

  • 嘿,它确实有帮助。但这会导致另一个问题。由于我有多个以rendered 作为子键的字段,如果将许多@Embedded 类命名为rendered,它会抱怨说“多个字段具有相同的columnName:已渲染”。以不同方式重命名它们不会读取值。
  • 您能否提供有关您尝试解析的错误和示例 json 的更多详细信息?
  • 这个问题就像title: { rendered: "foo" } },但是还有另外2个键,里面有renderedcontentexcerpt,这会导致错误Error:(8, 8) error: Multiple fields have the same columnName: rendered. Field names: title > rendered, content > rendered, excerpt > rendered.。我找到了附加前缀的解决方案,但在这种情况下,他们正在创建他们的 JSON 格式,在我的情况下,我获取了一个已经定义的格式,并且与 rendered 不同的名称不会显示任何内容。如果您想查看 JSON:skillpoint.com.br/wp-json/wp/v2/posts
  • @gamofe 请检查已编辑的答案。如果要操作 JSON 映射,请使用 Gson 或任何其他类似的解析器。由于映射变量与 JSON 键不同,因此应该出错。
  • 使用 GSON 的SerializedName 解决了它。您只需在答案中编辑一件事:其他 3 个类中的变量名称不能相同,只有序列化名称应为 rendered
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 2022-07-18
  • 2017-08-24
  • 2022-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多