https://kotlinlang.org logo
#android
Title
# android
t

T

05/29/2020, 12:01 PM
I want to extract the array data from the json response and store the data in my custom data class.
Copy code
data class NewsData (

    val author: String, val title: String,
    val url: String, val publishedAt: String
)
Copy code
class NewsViewModel : ViewModel() {

    // The internal MutableLiveData String that stores the most recent response
    private val _response = MutableLiveData<String>()

    // The external immutable LiveData for the response String
    val response: LiveData<String>
        get() = _response

    /**
     * Call getNewsData() on init so we can display status immediately.
     */
    init {
        getNewsData()
    }

    /**
     * Sets the value of the status LiveData to the News API status.
     */
    private fun getNewsData() {

        _response.value = NewsApi.retrofitService.getProperties().enqueue(
            object : Callback<ResponseBody> {
                override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                    _response.value = "Failure: " + t.message
                    //Log.i("response", t.message)
                }

                override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                    val root = JSONObject(response.body().toString())
                    val jsonArr = root.getJSONArray("articles")
                    val ob = jsonArr.getJSONObject(0)
                    val name = ob.getString("author")
                    _response.value = name
                }
            }).toString()
    }
}
This is the format of the json response.
o

Olenyov Kirill

05/29/2020, 12:25 PM
What’s the question? It’s much better to use for e.g. Gson library instead of parsing json manually with JsonObject/Array etc.
t

T

05/29/2020, 12:26 PM
Kindly help me with the library
o

Olenyov Kirill

05/29/2020, 12:33 PM
As I can see, you need to create outer class which will include the list of your NewsData. Something like this: data class NewsList(articles: List<NewsData>) and pass it to Gson.
t

T

05/29/2020, 12:34 PM
okay
but the json response returns a Json object and I don not know how to extract the array from it to be able to use it
o

Olenyov Kirill

05/29/2020, 12:38 PM
Can you show your plain json? I mean the text itself(response.body().toString())
t

T

05/29/2020, 12:38 PM
okay, getting that for you
Copy code
{
  "status": "ok",
  "totalResults": 38,
  "articles": [
    {
      "source": {
        "id": "cnn",
        "name": "CNN"
      },
      "author": "Faith Karimi, CNN",
      "title": "Minnesota sends 500 National Guard soldiers to Minneapolis and nearby areas as protests grow over George Floyd's death - CNN",
      "description": "Minnesota is sending more than 500 National Guard soldiers to Minneapolis and surrounding areas as protests erupted for a third night over the death of a black man while in police custody.",
      "url": "<https://www.cnn.com/2020/05/29/us/minneapolis-george-floyd-friday/index.html>",
      "urlToImage": "<https://cdn.cnn.com/cnnnext/dam/assets/200528234329-minneapolis-police-station-fire-super-tease.jpg>",
      "publishedAt": "2020-05-29T05:34:01Z",
      "content": "(CNN)Minnesota is sending more than 500 National Guard soldiers to Minneapolis and surrounding areas as protests erupted for a third night over the death of a black man while in police custody.\r\n\"Our… [+2576 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "New York Times"
      },
      "author": "Michael Levenson, Neil Vigdor",
      "title": "Inclusion of Transgender Student Athletes Violates Title IX, Trump Administration Says - The New York Times",
      "description": "Three female high school students in Connecticut had challenged a scholastic sports policy that allows transgender athletes to compete against them in track.",
      "url": "<https://www.nytimes.com/2020/05/29/us/connecticut-transgender-student-athletes.html>",
      "urlToImage": "<https://static01.nyt.com/images/2020/05/28/us/politics/28xp-transgender/merlin_169395210_06f0bab7-e873-4662-870b-08b11e475ca2-facebookJumbo.jpg>",
      "publishedAt": "2020-05-29T05:25:11Z",
      "content": "A high school sports policy in Connecticut that allows transgender students to participate in athletics based on their gender identity violates federal law and could cost the state federal education … [+6111 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "Billboard"
      },
      "author": "Jason Lipshutz",
      "title": "Lady Gaga's 'Chromatica' is the Summer Dance-Pop Escape We Needed - Billboard",
      "description": "",
      "url": "<https://www.billboard.com/articles/columns/pop/9392842/lady-gaga-chromatica-review-first-listen>",
      "urlToImage": "<https://static.billboard.com/files/2020/03/Lady-Gaga-press-2020-by-Norbert-Schoerner-billboard-1548-1583179375-1024x677.jpg>",
      "publishedAt": "2020-05-29T04:55:41Z",
      "content": "Id rather be dry, but at least Im alive, Lady Gaga sings on her new Ariana Grande duet, Rain On Me. Its a timely sentiment: this year has forced many of us to recognize that, while wed rather our cir… [+3410 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "CNBC"
      },
      "author": "Jabari Young",
      "title": "NFL owners approve exclusive renewal with Electronic Arts, alter distribution rule for CBS and FOX games - CNBC",
      "description": "NFL team owners approved a series of proposals, including a renewal of the league's exclusive video gaming rights with Electronic Arts. The firm's sports division produces the popular Madden NFL football series.",
      "url": "<https://www.cnbc.com/2020/05/28/nfl-owners-approve-exclusive-renewal-with-electronic-arts-alter-distribution-rule-for-cbs-and-fox-games.html>",
      "urlToImage": "<https://image.cnbcfm.com/api/v1/image/106556161-1590705238912pat.jpg?v=1590705313>",
      "publishedAt": "2020-05-29T04:24:00Z",
      "content": "It was business as usual on Thursday for the National Football League.\r\nLeague owners approved a series of proposals, including the renewal of the NFL's exclusive video gaming rights with Electronic … [+3229 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "ESPN"
      },
      "author": null,
      "title": "Chase Elliott ends week of misery with overdue Cup victory - ESPN",
      "description": "After disappointing finishes in the past two Cup Series races, Chase Elliott earned a little redemption when he won Thursday night's race at Charlotte Motor Speedway.",
      "url": "<https://www.espn.com/racing/nascar/story/_/id/29237980/chase-elliott-ends-week-misery-overdue-cup-victory>",
      "urlToImage": "<https://a4.espncdn.com/combiner/i?img=%2Fphoto%2F2020%2F0529%2Fr703309_1296x729_16%2D9.jpg>",
      "publishedAt": "2020-05-29T03:41:26Z",
      "content": "CONCORD, N.C. -- Chase Elliott's streak of bitter defeats in NASCAR's frantic first push of rescheduled races finally ended with his first Cup victory of the season.\r\nElliott won Thursday night in th… [+4890 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "Los Angeles Times"
      },
      "author": "Don Lee, Tracy Wilkinson",
      "title": "Trump likely to slap limited sanctions on China over Hong Kong crackdown - Los Angeles Times",
      "description": "U.S. advisors are debating sanctions against China for its crackdown on Hong Kong, but Trump appears to be leaning toward a limited response.",
      "url": "<https://www.latimes.com/politics/story/2020-05-28/trump-likely-limited-sanctions-china-hong-kong>",
      "urlToImage": "<https://ca-times.brightspotcdn.com/dims4/default/5ccc301/2147483647/strip/true/crop/2048x1075+0+38/resize/1200x630!/quality/90/?url=https%3A%2F%2Fcalifornia-times-brightspot.s3.amazonaws.com%2F08%2Fa8%2F16fa7371736b83babbed405b389b%2Fla-1509662680-6ptdrguolx-snap-image>",
      "publishedAt": "2020-05-29T03:34:37Z",
      "content": "Under political pressure to take a hard line against China for its crackdown on Hong Kong, President Trump instead is planning to impose relatively mild new sanctions on visas and Chinese access to t… [+9229 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "CNET"
      },
      "author": "Jessica Dolcourt",
      "title": "Stimulus check tracking tool still not working for you? Here are 11 possible reasons why - CNET",
      "description": "If you're having problems with the IRS' Get My Payment tool to track when your stimulus money is coming, we collected some common complaints.",
      "url": "<https://www.cnet.com/personal-finance/stimulus-check-tracking-tool-still-not-working-for-you-here-are-11-possible-reasons-why/>",
      "urlToImage": "<https://cnet1.cbsistatic.com/img/M2KRWPiKDphOnzF-pcJr1Cti2qU=/756x567/2020/04/15/710026b9-cd61-4dc7-bdef-507be40f7fde/money-bills-wallet-coins-dollars.jpg>",
      "publishedAt": "2020-05-29T02:36:15Z",
      "content": "We can help identify some of the frustrations you might be facing with the IRS' tracking tool for your stimulus money.\r\nAngela Lang/CNET\r\nFor the most up-to-date news and information about the corona… [+7853 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "<http://Eonline.com|Eonline.com>"
      },
      "author": "McKenna Aiello",
      "title": "YouTuber Myka Stauffer's Lawyers Speak Out After Adoption Controversy - E! NEWS",
      "description": "YouTube personality Myka Stauffer is facing criticism for \"rehoming\" son Huxley three years after he was adopted from China. Now, attorneys for Myka and husband James are speaking out.",
      "url": "<https://www.eonline.com/news/1156996/youtuber-myka-stauffer-s-lawyers-speak-out-after-facing-backlash-for-rehoming-adopted-son>",
      "urlToImage": "<https://akns-images.eonline.com/eol_images/Entire_Site/2020428/rs_600x600-200528095610-600-5mykas-tauffer-huxley-instagram.jpg?fit=around|600:467&crop=600:467;center,top&output-quality=90>",
      "publishedAt": "2020-05-29T02:28:36Z",
      "content": "YouTube personality Myka Stauffer and husband James Stauffer stand by their decision to place their adopted son in the care of another family. \r\nThe couple faced intense criticism after she revealed … [+849 chars]"
    },
    {
      "source": {
        "id": "cnn",
        "name": "CNN"
      },
      "author": "Ben Westcott and Steven Jiang, CNN",
      "title": "China is embracing a new brand of foreign policy. Here's what wolf warrior diplomacy means - CNN",
      "description": "There is a new brand of diplomacy taking hold in Beijing and its chief architects have a suitably fierce nickname to match their aggressive style -- they are the wolf warriors.",
      "url": "<https://www.cnn.com/2020/05/28/asia/china-wolf-warrior-diplomacy-intl-hnk/index.html>",
      "urlToImage": "<https://cdn.cnn.com/cnnnext/dam/assets/200527111102-wolf-warrior-ii-super-tease.jpg>",
      "publishedAt": "2020-05-29T02:25:00Z",
      "content": "Some politicians ignore the basic facts and make up countless lies and conspiracy theories concerning China. The longer the list, the more it says about how low the rumor-mongers are willing to go an… [+92 chars]"
    },
    {
      "source": {
        "id": "cbs-news",
        "name": "CBS News"
      },
      "author": "Irina Ivanova",
      "title": "More than 3 million Americans filed for unemployment last week, but claims are falling - CBS News",
      "description": "Some 42 million workers have lost their jobs since March — twice the number lost during the entire Great Recession.",
      "url": "<https://www.cbsnews.com/news/more-than-3-million-unemployment-claims-jobless-report-coronavirus-pandemic-2020-05-28/>",
      "urlToImage": "<https://cbsnews3.cbsistatic.com/hub/i/r/2020/05/07/0bc885f2-e97d-41f5-a941-37973dcd22df/thumbnail/1200x630/d53502a252e9108a7dd85c551b31e137/cbsn-fusion-32-million-unemployment-claims-filed-last-week-for-a-33-million-total-thumbnail-480746-640x360.jpg>",
      "publishedAt": "2020-05-29T02:24:51Z",
      "content": "More than 3 million Americans applied for unemployment benefits last week, raising to more than 42 million the number of workers who have lost jobs since the coronavirus crippled the economy.\r\nSome 2… [+2030 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "Daily Beast"
      },
      "author": "Tim Teeman",
      "title": "'Larry Kramer Changed My Life.' Ellen Barkin, Joel Grey, Anthony Rapp, and Others Recall a 'Hero' and Friend - The Daily Beast",
      "description": "After Larry Kramer's death, Ellen Barkin, Joel Grey, Anthony Rapp, Matt Bomer, Michelangelo Signorile, Sean Strub, Daryl Roth, and William J. Mann share their memories of a friend.",
      "url": "<https://www.thedailybeast.com/larry-kramer-changed-my-life-ellen-barkin-joel-grey-anthony-rapp-and-others-recall-a-hero-and-friend>",
      "urlToImage": "<https://img.thedailybeast.com/image/upload/c_crop,d_placeholder_euli9k,h_1687,w_3000,x_0,y_0/dpr_2.0/c_limit,w_740/fl_lossy,q_auto/v1590697278/200528-teeman-kramer-tease_hrntpf>",
      "publishedAt": "2020-05-29T01:47:00Z",
      "content": "Larry Kramer, the late LGBTQ and AIDS activist, author and playwright, has been much praised and analyzed over the last 24 hours. But Larry Kramer was also both a friend and professional collaborator… [+26702 chars]"
    },
    {
      "source": {
        "id": "fox-news",
        "name": "Fox News"
      },
      "author": "Joseph Wulfsohn",
      "title": "<http://FactCheck.org|FactCheck.org> calls out Biden's false claims, exaggerations from 'Breakfast Club' interview - Fox News",
      "description": "Joe Biden sparked a firestorm of controversy last Friday for his \"you ain't black\" remark, but he may be facing more problems from his interview with \"Breakfast Club\" radio host Chalamagne tha God.",
      "url": "<https://www.foxnews.com/media/factcheckorg-calls-out-bidens-false-claims-exaggerations-from-breakfast-club-interview>",
      "urlToImage": "<https://static.foxnews.com/foxnews.com/content/uploads/2020/05/Biden-Charlamagne_Getty.jpg>",
      "publishedAt": "2020-05-29T01:34:39Z",
      "content": "Joe Biden sparked a firestorm of controversy last Friday for his \"you ain't black\" remark, but he may be facing more problems from his interview with \"Breakfast Club\" radio host Charlamagne tha God.\r… [+3202 chars]"
    },
    {
      "source": {
        "id": "the-washington-post",
        "name": "The Washington Post"
      },
      "author": "Ariana Eunjung Cha",
      "title": "Children with perplexing syndrome linked to covid-19 may be experiencing deadly 'cytokine storm' - The Washington Post",
      "description": "New York physicians propose early theory, detailing four cases that were remarkably similar.",
      "url": "<https://www.washingtonpost.com/health/2020/05/28/children-with-perplexing-syndrome-linked-covid-19-may-be-experiencing-deadly-cytokine-storm/>",
      "urlToImage": "<https://www.washingtonpost.com/wp-apps/imrs.php?src=https://arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/OBGRCZEW5II6VB5DELJSII2WGY.jpg&w=1440>",
      "publishedAt": "2020-05-29T01:05:34Z",
      "content": "A study about the children, ages 13, 12, 10, and 5, published in the American Journal of Emergency Medicine, provides the first detailed look at the rapid progression of a mysterious syndrome linked … [+6829 chars]"
    }
  ]
}
o

Olenyov Kirill

05/29/2020, 12:52 PM
The same. It should work. data class NewsList(articles: List<NewsData>) How do you use Gson?
t

T

05/29/2020, 12:55 PM
okay, trying it out..Thanks
I was trying the get the size of the list but I got an error message Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $
o

Olenyov Kirill

05/29/2020, 1:04 PM
Can you show me the code?)
t

T

05/29/2020, 1:04 PM
sure
This is the data class
Copy code
data class NewsData (val articles: List<NewsData>)
This is the api service
Copy code
private const val BASE_URL = "<https://newsapi.org/v2/>"
private const val API_KEY = "1234abc"

private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create())
    .baseUrl(BASE_URL)
    .build()

interface NewsApiService {
    @GET("top-headlines?country=us&apiKey=${API_KEY}")
    fun getProperties():
            Call<List<NewsData>>
}

object NewsApi  {
    val retrofitService : NewsApiService by lazy {
        retrofit.create(NewsApiService::class.java) }
}
This is the model
Copy code
class NewsViewModel : ViewModel() {

    // The internal MutableLiveData String that stores the most recent response
    private val _response = MutableLiveData<String>()

    // The external immutable LiveData for the response String
    val response: LiveData<String>
        get() = _response

    /**
     * Call getNewsData() on init so we can display status immediately.
     */
    init {
        getNewsData()
    }

    /**
     * Sets the value of the status LiveData to the News API status.
     */
    private fun getNewsData() {

        _response.value = NewsApi.retrofitService.getProperties().enqueue(
            object : Callback<List<NewsData>> {
                override fun onFailure(call: Call<List<NewsData>>, t: Throwable) {
                    _response.value = "Failure: " + t.message
                    //Log.i("response", t.message)
                }

                override fun onResponse(call: Call<List<NewsData>>, response: Response<List<NewsData>>) {
                    _response.value = "Success: ${response.body()?.size} News retrieved"
                }
            }).toString()
    }
}
o

Olenyov Kirill

05/29/2020, 1:14 PM
It seems you didn’t pass your “moshi” field to MoshiConverterFactory.create(…)
t

T

05/29/2020, 1:16 PM
I just did that, same error
o

Olenyov Kirill

05/29/2020, 1:19 PM
Actually, i have never used Moshi. But google shows that you may need to annotate classes with @field:Json(name = “xxxxxx”)..
t

T

05/29/2020, 1:20 PM
okay, let me try that... I am a beginner in kotlin and android development
@Olenyov Kirill Thank you for the assistance and your time. I appreciate it
723 Views