Seb
Seb

Reputation: 3215

Extract data from json to a kotlin data class

I have to use a json file in my app and I have defined a different data classes to represent the data itself. the json is stored locally in the app.

the json look like:

[
   {
      "id":987847,
      "type":"FixtureUpcoming",
      "homeTeam":{
         "id":43,
         "name":"Manchester City",
         "shortName":"Man City",
         "abbr":"MNC",
         "alias":"t43"
      },
      "awayTeam":{
         "id":8,
         "name":"Chelsea",
         "shortName":"Chelsea",
         "abbr":"CHL",
         "alias":"t8"
      },
      "date":"2019-02-10T16:00:00.000Z",
      "competitionStage":{
         "competition":{
            "id":8,
            "name":"Premier League"
         }
      },
      "venue":{
         "id":2691,
         "name":"Etihad Stadium"
      },
      "state":"preMatch"
   },
   {
      "id":1036495,
      "type":"FixtureUpcoming",
      "homeTeam":{
...
]

So I have created a data class which represent an element of this array as below:

data class FixtureItem(
        var id: Int,
        var type: String,
        var homeTeam: Team,
        var awayTeam: Team,
        var date: String,
        var competitionStage: List<Competition>,
        var venue: Venue,
        var state: String
)

and some other elements are also a defined class like Team or Venue..

data class Team(
     var id: Int,
     var name: String,
     var shortName: String,
     var abbr: String,
     var alias: String
)

What is the best way to translate this json using data class ? overall, this json is display in a recyclingview.

Any idea how to properly extract it and use it in a recyclerview ?

Thanks

Upvotes: 0

Views: 928

Answers (1)

tyczj
tyczj

Reputation: 73753

Personally I would use Moshi or KotlinX Serialization to parse your data into objects

Moshi adds a few extra dependencies required for kotlin use and KotlinX Serialization was made by the kotlin team in 100% kotlin plus supports kotlin multiplatform if that's of any interest. It is fairly new however and just went 1.0 a few weeks ago.

cant really go wrong with either though

Upvotes: 1

Related Questions