skip to Main Content

I’m sending API Call and getting response like that

{ "12312412312124123124": { "id": "12312412312124123124", "content": [ { "id": 41419969} ] },
"141412312412312521": { "id": 141412312412312521", "content": [ { "id": 41419969} ] }}

how can I handle to parse this json object or create data class for it , I’ve searched for custom deserialization but can’t find answer…

This is my call execution code

   builder.build().newCall(request).execute().use { response ->

        if (response.isSuccessful) {
            val responseBody = response.body?.string()
          
            if (!responseBody.isNullOrBlank()) {
                val readings = gson.fromJson(responseBody, MyClassForParsing::class.java)
                
            } else {
                println("Response body is empty.")
            }
        } else {
            println("Request failed with code: ${response.code}")
        }
    }

2

Answers


  1. i am using retrofit to do networking. u can processing json to variabel too

    u can read it here: https://betterprogramming.pub/how-to-use-retrofit-for-networking-in-android-for-beginners-ef6bae5ef113

    Login or Signup to reply.
  2. Response Data Class (Don’t forget to add @SerializedName)

    data class ResponseType(
        var id: String?,
        var content: List<Content>?
    )
    
    data class Content(
        var id: Int?
    )
    

    Variable key values ​​are available in the relevant json data

    interface API {
        @GET("yourEndPoint")
        fun yourFunction(): Call<HashMap<String, ResponseType>>
    }
    

    Last Step call enqueue

    val call = service.getYourApiRequestFunction()
    
    call.enqueue(object : Callback<HashMap<String, ResponseType>> {
        override fun onResponse(
            call: Call<HashMap<String, ResponseType>>,
            response: Response<HashMap<String, ResponseType>>
        ) {
            if (response.isSuccessful) {
                val responses = response.body()
                // your process - responses type ==== > HashMap<String, ResponseType>
            }
        }
    
        override fun onFailure(call: Call<HashMap<String, ResponseType>>, t: Throwable) {
            // your error case
        }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search