134

我有这样的 Java POJO 类:

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

我有一个像这样的 Kotlin 数据类

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

java - 如何为java变量中的注释提供json key任何变量?kotlin data class@SerializedName

4

3 回答 3

276

数据类:

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

到 JSON:

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

来自 JSON:

val json = getJson()
val topic = gson.fromJson(json, Topic::class.java)
于 2017-05-22T17:29:57.090 回答
21

基于Anton Golovin的回答

细节

  • Gson 版本:2.8.5
  • 安卓工作室 3.1.4
  • Kotlin 版本:1.2.60

解决方案

创建任意类数据并继承JSONConvertable接口

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

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

用法

数据类

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

来自 JSON

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

转 JSON

val json = object.toJSON()
于 2018-08-15T14:20:41.430 回答
3

您可以在 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
}

而且对于嵌套类,如果有嵌套对象,您也可以使用相同的方法。只需为类提供序列化名称。

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

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

}

因此,如果从服务器获得响应,每个键都将映射到 JOSN。

另外,将 List 转换为 JSON:

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

android 从 JSON 转换为 Object:

val json = getJson()
val topic = gson.fromJson(json, Topic::class.java)
于 2019-08-23T13:48:17.430 回答