Kotlin Data Class from Json using GSON

后端 未结 3 2020
梦毁少年i
梦毁少年i 2020-12-12 17:55

I have Java POJO class like this:

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

a

3条回答
  •  死守一世寂寞
    2020-12-12 18:36

    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)
    

提交回复
热议问题