Home > Software design >  How to get list from response in kotlin
How to get list from response in kotlin

Time:08-28

I have this api that returns a list as response

Here's the API https://animension.to/public-api/search.php?search_text=&season=&genres=&dub=&airing=&sort=popular-week&page=2

this returns a response string in list format like this

[["item", 1, "other item"], ["item", 2, "other item"]]

How do I convert this so that I can use it as list not string data type

CodePudding user response:

One way is to use Kotlinx Serialization. It doesn't have direct support for tuples, but it's easy to parse the input as a JSON array, then manually map to a specific data type (if we make some assumptions).

First add a dependency on Kotlinx Serialization.

// build.gradle.kts

plugins {
  kotlin("jvm") version "1.7.10"
  kotlin("plugin.serialization") version "1.7.10" 
  // the KxS plugin isn't needed, but it might come in handy later!
}

dependencies {
  implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.0")
}

(See the Kotlinx Serialization README for Maven instructions.)

Then we can use the JSON mapper to parse the result of the API request.

import kotlinx.serialization.json.*

fun main() {
  val inputJson = """ 
     [["item", 1, "other item"], ["item", 2, "other item"]]
  """.trimIndent()

  // Parse, and use .jsonArray to force the results to be a JSON array
  val parsedJson: JsonArray = Json.parseToJsonElement(inputJson).jsonArray

  println(parsedJson)
  // [["item",1,"other item"],["item",2,"other item"]]
}

It's much easier to manually map this JsonArray object to a data class than it is to try and set up a custom Kotlinx Serializer.

import kotlinx.serialization.json.*

fun main() {
  val inputJson = """ 
     [["item", 1, "other item"], ["item", 2, "other item"]]
  """.trimIndent()

  val parsedJson: JsonArray = Json.parseToJsonElement(inputJson).jsonArray

  val results = parsedJson.map { element ->
    val data = element.jsonArray
    // Manually map to the data class. 
    // This will throw an exception if the content isn't the correct type...
    SearchResult(
      data[0].jsonPrimitive.content, 
      data[1].jsonPrimitive.int,
      data[2].jsonPrimitive.content,
    )
  }

  println(results)
  // [SearchResult(title=item, id=1, description=other item), SearchResult(title=item, id=2, description=other item)]

}

data class SearchResult(
  val title: String,
  val id: Int,
  val description: String,
)

The parsing I've defined is strict, and assumes each element in the list will also be a list of 3 elements.

  • Related