syncended
syncended

Reputation: 91

Get only one parameter from json object via retrofit(gson)

Json:

JSON

I need to get only id field from source. Data class:

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

Convertor factory is GsonConvertorFactory

Upvotes: 0

Views: 749

Answers (1)

user2340612
user2340612

Reputation: 10733

In the JSON you provided, source is a complex object, so you can't define it as a string unless you create a custom deserialiser. A quick way to get this working, though, is to create another set of classes to mimic the JSON structure, like this:

data class Source(
        val id: String
)

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

Then you can use it this way:

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)
}

This prints: Article(source=Source(id=bbc-news), author=BBC News, title=Afrobeat pioneer Tony Allen dies aged 79).

Upvotes: 1

Related Questions