Sazzad Hissain Khan
Sazzad Hissain Khan

Reputation: 40186

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?

Upvotes: 3

Views: 3908

Answers (1)

anro
anro

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

Related Questions