Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

java - Kotlin Data Class from Json using GSON

I have Java POJO class like this:

class Topic {
    @SerializedName("id")
    long id;
    @SerializedName("name")
    String name;
}

and I have a Kotlin data class Like this

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

How to provide the json key to any variables of the kotlin data class like the @SerializedName annotation in java variables ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...