Search code examples
androidjsonkotlinnetwork-programmingretrofit

how to parse Json data with custom deserialization


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}")
        }
    }

Solution

  • I've found an answer in case if it will help someone I'll post it here...

    first you need to get as response JsonObject , like this :

    suspend fun yourFunction() : JsonObject
    

    then you need to store that JsonObject in a variable

    val call = service.yourFunction()
    

    then you need this function

     fun parseStringParameterWithGsonKotlinDynamicKey(stringParameter: String): Map<String, Any?> {
        val gson = Gson()
        val jsonObject = gson.fromJson(stringParameter, JsonObject::class.java)
    
        val parsedParameters = mutableMapOf<String, Any?>()
        for ((key, value) in jsonObject.entrySet()) {
            parsedParameters[key] = value
        }
    
        return parsedParameters
    }
    

    create another variable and call this function passing JsonObject as a String , like this

    val dfg= parseStringParameterWithGsonKotlinDynamicKey(call.toString())
    

    at that point you'll get parsed json object with your object in it and you can iterate and get your items like this

    dfg.entries.forEach { item ->
           val devices = Gson().fromJson(item.value.toString(),YuorDataClass::class.java)
       }
    

    I hope someone would find an answer and I will make someones day!

    P.S. Thanks who responded!