简体   繁体   English

来自 Json 的 Kotlin 数据类使用 GSON

[英]Kotlin Data Class from Json using GSON

I have Java POJO class like this:我有这样的 Java POJO 类:

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

and I have a Kotlin data class Like this我有一个 Kotlin 数据类像这样

 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 ?如何向kotlin data class任何变量(如 java 变量中的@SerializedName注释)提供json key

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:到 JSON:

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

from JSON:来自 JSON:

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

Based on answer of Anton Golovin基于Anton Golovin 的回答

Details详情

  • Gson version: 2.8.5 Gson 版本:2.8.5
  • Android Studio 3.1.4安卓工作室 3.1.4
  • Kotlin version: 1.2.60科特林版本:1.2.60

Solution解决方案

Create any class data and inherit JSONConvertable interface创建任意类数据并继承JSONConvertable接口

interface JSONConvertable {
     fun toJSON(): String = Gson().toJson(this)
}

inline fun <reified T: JSONConvertable> String.toObject(): T = Gson().fromJson(this, T::class.java)

Usage用法

Data class数据类

data class User(
    @SerializedName("id") val id: Int,
    @SerializedName("email") val email: String,
    @SerializedName("authentication_token") val authenticationToken: String) : JSONConvertable

From JSON来自 JSON

val json = "..."
val object = json.toObject<User>()

To JSON到 JSON

val json = object.toJSON()

You can use similar in Kotlin class您可以在 Kotlin 类中使用类似的

class InventoryMoveRequest {
    @SerializedName("userEntryStartDate")
    @Expose
    var userEntryStartDate: String? = null
    @SerializedName("userEntryEndDate")
    @Expose
    var userEntryEndDate: String? = null
    @SerializedName("location")
    @Expose
    var location: Location? = null
    @SerializedName("containers")
    @Expose
    var containers: Containers? = null
}

And also for nested class you can use same like if there is nested object.而且对于嵌套类,您可以使用相同的方法,就像有嵌套对象一样。 Just provide Serialize name for the Class.只需为类提供序列化名称。

@Entity(tableName = "location")
class Location {

    @SerializedName("rows")
    var rows: List<Row>? = null
    @SerializedName("totalRows")
    var totalRows: Long? = null

}

so if get response from the server each key will map with JOSN.所以如果从服务器得到响应,每个键都将与 JOSN 映射。

Alos, convert List to JSON: Alos,将列表转换为 JSON:

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

ndroid convert from JSON to Object: ndroid 从 JSON 转换为 Object:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM