Reputation: 40186
I wonder what is the way to convert a Kotlin
data class into its equivalent json
string. Json keys
should be configurable.
Let's say I have a class,
data class Student(name: String?, roll: Int?, mark: Int?) {
}
I want to make a Json from this Student
object where keys will be,
stundent_name, stundent_roll, stundent_mark
Moreover, I may also need to make a json from list of student with key students
. How can I do so? I know using Gson
I can create object from json string. How to do the reverse?
Upvotes: 3
Views: 3908
Reputation: 1388
data class Student(
@SerializedName("stundent_name")
val name: String?,
@SerializedName("stundent_roll")
val roll: Int?,
@SerializedName("stundent_mark")
val mark: Int?
)
And the code for convertion is:
val gson = Gson()
val student = Student("John", 1, 5)
gson.toJson(student)
This code makes String like this:
{"stundent_mark":5,"stundent_name":"John","stundent_roll":1}
And if you need to create JsonArray, just do the same with your List of students:
gson.toJson(list)
Upvotes: 2