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 ?

推荐答案

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)

Json相关问答推荐

从Razor Pages的AJAX Json呈现DataTables问题.Net GET

带有PowerShell内核的NewtonSoft json.Net的奇怪行为

从json数组中删除特定元素

如何在改装Android中将ResponseBody转换为JSONObject

数据到jsonObject到数据到 struct 是可能的吗?

递归解码嵌套列表(具有任意深度的列表列表)

使用 Power BI 中的 Deneb 视觉效果绘制面积图中的 X 轴日期

在Flutter 中将 map 的 Json 转换为 list

Oracle Apex - 将 JSON 对象分配给变量以返回

SwiftUI:如何使用 0 索引数组键为 JSON 添加类型

缺少所需的请求正文内容:org.springframework.web.method.HandlerMethod$HandlerMethodParameter

如何为所有 API 端点全局设置 http.ResponseWriter Content-Type 标头?

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

如何在 Rails 模型中验证字符串是否为 json

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

将 json 转换为 C# 数组?

IE10/11 Ajax XHR 错误 - SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3

如何使用 Json.NET 反序列化可以是两种不同数据类型的 JSON 属性

来自 Gson 的 JSON 字符串:删除双引号

如何在 React js 中解析本地 JSON 文件?