Amelie Fowl
Amelie Fowl

Reputation: 83

How to get a nested object in JSON in Kotlin?

I've created the classes of Eqs and Service, got the service objects but can't get the list of eqs. Can anyone help me with this? This the Eqs class

 data class Eqs(
  val name: String,
  val imageUrl: String,
  val description: String?,
  val responsible: String
)

That's the Service class which gets its values

data class Service(
  val title: String,
  val servings: Int,
  val eqs: List<Eqs>
    )  {

  companion object {

    fun getServicesFromFile(filename: String, context: Context): ArrayList<Service> {
      val serviceList = ArrayList<Service>()

      try {
        // Load data
        val jsonString = loadJsonFromAsset("services.json", context)
        val json = JSONObject(jsonString)
        val services = json.getJSONArray("services")


        (0 until services.length()).mapTo(serviceList) {
          Service(services.getJSONObject(it).getString("title"),
              services.getJSONObject(it).getInt("servings"),
        }
      } catch (e: JSONException) {
        e.printStackTrace()
      }

      return serviceList
    }

I can't get the List of Eqs in my getServicesFromFile function. How to parse and get it correctly?

Upvotes: 0

Views: 4164

Answers (2)

Sanush
Sanush

Reputation: 325

  1. Use Json to Kotlin plugin
  2. In tool bar of android studio Code >> Generate and copy & paste you API into it and give the class name
    [
        {
            "id": 1,
            "name" : "Madoldoowa",
            "description": "Madol Doova (මඩොල් දූව) is a children's novel and coming-of-age story written by Sri Lankan writer

Martin Wickramasinghe and first published in 1947", "language" : "Sinhala", "isbn" : "ISBN232673434", "file_size" : 300, "no_of_pages" : 500, "price" : 970, "ratings" : "5.1K", "cover_page" : "https://upload.wikimedia.org/wikipedia/en/5/5c/MadolDoova.jpg", "author" : { "name" : "Martin Wickramasinghe" } ]

data class Model(
    val author: Author,
    val cover_page: String,
    val description: String,
    val file_size: Int,
    val id: Int,
    val isbn: String,
    val language: String,
    val name: String,
    val no_of_pages: Int,
    val price: Int,
    val ratings: String
)

data class Author(
    val name: String
)

Upvotes: 1

Mehrbod Khiabani
Mehrbod Khiabani

Reputation: 543

I recommend you to use Jackson library. It's simple and saves you a lot of time. You can find it's documentation here: https://www.baeldung.com/jackson-kotlin

You also can use some websites to generate the data class needed for Jackson like https://app.quicktype.io/

Upvotes: 1

Related Questions