Home > front end >  How to generate dynamic json object for request body
How to generate dynamic json object for request body

Time:03-21

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>?

     )

CodePudding user response:

From your description, this is a bad design decision from backend side You should have one parameter questions on which you will pass list of Question classes like this

First create a separate data class Question

data class Question (
val key:String, 
val value:String)

than set list of this data class as Type of questions parameter in a request model like this

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

 )

I'm assuming you are using Gson library for converting data classes to json and vice versa

Solution for given situation is to create Separate request models for each number of questions you send to BE,

BUT i would strongly advise not to do this and make backend guys to change how your api works

CodePudding user response:

The questions should be in a json array. Example:

 "quiz": {  
   "name":"Jacob",
   "sid": "STD_500",
   "questions" : [
     {"key": "questionOne", "value": ""},
     {"key": "questionTwo", "value": ""},
   ]
 }

CodePudding user response:

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

  • Related