erluxman erluxman - 1 year ago 265
Java Question

Kotlin Data Class from Json using GSON

I Have a JSON Like this :

"topic": {
"id": 3,
"name": "Variables declaration",
"image": "xxx.xxx.xxx",
"description": "Variable declaration is basically booking memory for data being used in program"


}

and I have a Kotlin Data Class Like this

data class Topic(val id: Long, val name: String, val image: String, val description: String)


But I could not figure out a way to serialize/deserialize
data class <-> Json
like we used to do with
java POJO <-> Json
using
GSON
like this

@SerializedName("id")
long id;
@SerializedName("name")
String name;
@SerializedName("image")
String image;
@SerializedName("description")
String description;


Because I could not find a way to provide the
json selector
to any variables of the
kotlin data class
.

Does anyone have any idea about how it is done ?
Thanks in advance.

Answer Source

Data class:

data class Topic(@SerializedName("id") val id: Long, @SerializedName("name") val name: String, @SerializedName("image") val image: String, @SerializedName("description") val description: String)

to JSON:

val gson = Gson()
val json = gson.toJson(topic)

from JSON:

val json = getJson()
val topic = gson.fromJson(json, Topic::class.java)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download