Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a data class into JSON string for Kotlin?

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?

like image 551
Sazzad Hissain Khan Avatar asked Nov 25 '25 21:11

Sazzad Hissain Khan


1 Answers

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)
like image 167
anro Avatar answered Nov 27 '25 10:11

anro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!