Kotlin Json 与 Data Class

  1. 定义 Data Class

    1
    2
    3
    4
    5
    6
    data class Topic(
    @SerializedName("id") val id: Long,
    @SerializedName("name") val name: String,
    @SerializedName("image") val image: String,
    @SerializedName("description") val description: String
    )
  2. 转换Json

    1
    2
    val gson = Gson()
    val json = gson.toJson(topic)
  3. Json转Class

    1
    2
    val json = getJson()
    val topic = gson.fromJson(json, Topic::class.java)