Search code examples
androidkotlinretrofit

How to get data from api using retrofit and deserialiaze it?


I would like to download data using retrofit.

This is my API: https://burgers1.p.rapidapi.com/burgers

interface:

interface DishesApi {

    @Headers(
        value =
        ["X-RapidAPI-Key: 05fefddc5amshe82caa1862a2f8cp15fb97jsn1ee9dd9eb288",
            "X-RapidAPI-Host: burgers1.p.rapidapi.com"]
    )
    @GET("burgers")
    suspend fun getBurgers(): List<DishResponse>

data from Api as JsonElement in deserializer

{"id":0,"name":"Tribute Burger","restaurant":"Honest Burgers","web":"www.honestburgers.co.uk","description":"A mouth-watering honest beef burger","ingredients":["beef","american cheese","burger sauce","french mustard","pickes","onion","lettuce"],"addresses":[{"addressId":0,"number":"75","line1":"Venn Street","line2":"Clapham","postcode":"SW4 0BD","country":"United Kingdom"}]}


class DishResponseAdapter : JsonDeserializer<List<DishResponse>>,
    JsonSerializer<List<DishResponse>> {

    override fun deserialize(
        json: JsonElement?,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): List<DishResponse> {
        Log.d("mojjsonwylogowany", json.toString())
        val inputJson = Gson().fromJson(json!!.toString(), Array<DishResponse>::class.java).asList()
        return inputJson
    }

    override fun serialize(
        src: List<DishResponse>?,
        typeOfSrc: Type?,
        context: JsonSerializationContext?
    ): JsonElement {
        return when (src) {
            null -> JsonNull.INSTANCE
            else -> JsonPrimitive(src.toString())
        }
    }


}

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: pl.gda.wsb.firebaseapp, PID: 6784
    com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $


I would like to get the data in the List in kotlin, how to achieve this?


Solution

  • First of all,

    • you get List so it is correct. you get List so it is correct.
    • you do not need any additional deserialization so delete this adnotation and this class
    • in your usecase check if you emit data if you use flow or something like that