3

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?

1 Answer 1

2
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.