Search code examples
androidkotlinretrofit

How to generate dynamic json object for request body


In the Request body below, the number of value "questionOne", "questionTwo", etc changes for each student. How can i dynamically generate request body to fit the changing value of the key and value.

Sample request one

"quiz": {  
   "name":"Jacob",
   "sid": "STD_500",
   "questionOne":"",
   "questionTwo":""
}

Sample request two

"quiz": {  
    "name":"Annie",
    "sid": "STD_200",
    "questionOne":"",
    "questionTwo":""
    "questionThree":"",
    "questionFour":""
}

Data class:

data class Quiz (
    val name : String?,
    val sid : String?,
     val questions: HashMap<String, String>?

     )


Solution

  • I suppose the only way would be to define quiz as being a HashMap instead of a Quiz object. I'm guessing you now have a RequestBody somewhere something like this?

    data class RequestBody(
        val quiz: Quiz
    )
    

    Then change it to

    data class RequestBody(
        val quiz: HashMap<String,String>
    )
    

    But it's kind of a bad design like this, I suggest to work out with the backend a solution as proposed by Tornike's answer