仅通过Retrofit(gson)从json对象获取一个参数

问题描述 投票:0回答:1

Json:

“

我只需要从源获取id字段。数据类别:

data class Article(
    val sourceId: String,
    val author: String,
    val title: String,
    ...
)

转换器工厂是GsonConvertorFactory

json kotlin gson retrofit
1个回答
0
投票

在您提供的JSON中,source是一个复杂的对象,因此除非您创建custom deserialiser,否则无法将其定义为字符串。但是,一种快速实现此目的的方法是创建另一组类来模仿JSON结构,如下所示:

data class Source(
        val id: String
)

data class Article(
        val source: Source,
        val author: String,
        val title: String
)

然后您可以通过这种方式使用它:

fun main() {
    val json = """ {
    "source": {
      "id": "bbc-news",
      "name": "BBC News"
    },
    "author": "BBC News",
    "title": "Afrobeat pioneer Tony Allen dies aged 79"
}
""".trimIndent()

    val gson = GsonBuilder().create()

    val article = gson.fromJson(json, Article::class.java)
    println(article)
}

此打印:Article(source=Source(id=bbc-news), author=BBC News, title=Afrobeat pioneer Tony Allen dies aged 79)

© www.soinside.com 2019 - 2024. All rights reserved.