3.19 (Exercise) Parse News Response

Now we’ve covered everything that we need to finally parse our news response.

The starting code for this exercise is on parse_news_start branch.

Here is what the sample response for a breaking news endpoint looks like → https://newsdata.io/breaking-news-api

And this is what our Article data class looks like:

@Serializable
data class Article(
    val id: String = "",
    val source: String,
    val pubDate: String,
    val title: String,
    val link: String,
    val imageUrl: String? = null,
    val keywords: List<String> = emptyList(),
)

For the most part you don’t need to change anything here, but you will need to map the newsData.io response fields to our Article class fields:

Don’t worry about displaying the imageUrl as of now. We’ll cover that later.

Now our NewsDataRepo returns a List<Article>

interface NewsDataRepo {
    suspend fun getNewsData(): List<Article>
}

But our the API will return to you a wrapper around results. You already have that in your code:

@Serializable
data class ArticlesResponse(
   val status: String,
   val totalResults: Int,
   val results: List<Article>
)

So when you do GET - you will first need to cast it to ArticlesResponse and then extract results which is our List<Article>

Keep in mind, though, that once you start casting, all of the problems that you have with your JSON (like missing fields, null fields, wrong naming, etc.) will start to appear. So remember to reference the previous lesson to know how to fix them.

Also, don’t forget to return your results instead of the emptyList() we have here:

    override suspend fun getNewsData(): List<Article> {
        httpClient.get("<https://newsdata.io/api/1/latest?apikey=${BuildKonfig.API_KEY}>")
        return emptyList()
    }

Once you do all of this - you should see the latest news articles showing up in the UI (albeit without images) 🙂

Complete and Continue  
Discussion

0 comments