Categories: java, android, json, kotlin, retrofit

Retrofit sending Pojo as form data

1 answer

Are there any build in way to convert java/kotlin pojo to Form data object. For example if i have two classes

data class Student(         var id: Int,         var name: String,         var age: Int )  data class College     (         var id: Int,         var address: String,         var students: Array<Student> ) 

and array of this objects would be like this in JSON

[   {     "id": 1,     "address": "12 Lincoln Street",     "students":      [       {         "id": 1,         "name": "Mike",         "age": 17       },       {         "id": 2,         "name": "Ann",         "age": 18       },       {         "id": 2,         "name": "Bob",         "age": 20       }     ]   },   {     "id": 2,     "address": "544 Peninsula Street Brooklyn",     "students":      [       {         "id": 4,         "name": "Tom",         "age": 17       },       {         "id": 5,         "name": "Liza",         "age": 21       },       {         "id": 6,         "name": "Rachel",         "age": 22       }     ]   } ] 

Can i somehow covert it automatically to Form Data to something like this?

college[0][id] = 1 college[0][address] = "12 Lincoln Street" college[0][students][0][id] = 1 college[0][students][0][name] = "Mike" college[0][students][0][age] = 17 college[0][students][1][id] = 2 college[0][students][1][name] = "Ann" college[0][students][1][age] = 18 college[0][students][2][id] = 3 college[0][students][2][name] = "Bob" college[0][students][2][age] = 20 college[1][id] = 2 college[1][address] = "544 Peninsula Street Brooklyn" college[1][students][0][id] = 4 college[1][students][0][name] = "Tom" college[1][students][0][age] = 17 college[1][students][1][id] = 5 college[1][students][1][name] = "Liza" college[1][students][1][age] = 21 college[1][students][2][id] = 3 college[1][students][2][name] = "Rachel" college[1][students][2][age] = 22 

Maybe there are some java/kotlin libraries that can convert Json string to form data?

Received answer to this question:
The best answer according to the author of the question:

You can create 2 model (pojo class):

data class Student(     @Expose     @SerializedName("id")     var id: Int,     @Expose     @SerializedName("name")     var name: String,     @Expose     @SerializedName("age")     var age: Int )  data class College(     @Expose     @SerializedName("id")     var id: Int,     @Expose     @SerializedName("address")     var address: String,     @Expose     @SerializedName("students")     var students: List<Student> ) 

Then parse from json to object like that:

gson.fromJson(jsonString, Student::class.java)  // or  gson.fromJson(jsonString, College::class.java 

Hope this help!