arrays - 如何在 kotlin 中声明一个 json 数组
问题描述
我是 kotlin 和 Android Studio 的初学者,我正在尝试在数据类中声明一个 json 数组。这个类用于存储我从我的 api 获得的数据,但是 Json 有点复杂,我不知道如何用 moshi 声明一个 Json 数组。
这是我的Json:
{
_id : String,
name : String,
type : String,
stateList : [{
date: Integer,
source : String,
variables:[{
name: String,
value: String,
}]
}]
}
这是我的尝试:
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.baseUrl(BASE_URL)
.build()
interface MyApiService {
@GET("allDevice")
fun getProperties(): Deferred<List<Device>>
}
object MyApi {
val retrofitService : MyApiService by lazy { retrofit.create(MyApiService::class.java) }
}
class State(
@Json(name = "date") val date: Integer,
@Json(name = "source") val source: String,
val stateList: List<variable>)
class variable(
@Json(name = "name") val name: String,
@Json(name = "value") val value: String
)
data class Device(
val _id: String,
val stateList: List<State>,
val type: String,
val name: String)
我想这不是声明我的 Json 的好方法,那么正确的方法是什么?
解决方案
我认为您应该将类更改State
为这样的(将变量名称与 json 属性名称匹配):
class State(
@Json(name = "date") val date: Integer,
@Json(name = "source") val source: String,
val variables: List<variable>
)
推荐阅读
- oracle - 如何从 oracle 命令发送电子邮件?
- php - PHP 肥皂结果状态正常,但没有任何项目。SOAPUI 也提供状态和项目
- javascript - Alphavantage 的谷歌脚本给出了奇怪的结果
- java - 无法在 android studio 上启动应用程序是否显示 java.lang.NullPointerException:
- android - 向下滚动后如何自动隐藏状态栏?
- amazon-web-services - 如何检测用于登录的身份提供者?
- python - 如何修复只读文件系统错误python
- javascript - 如何在 SetTimeout 上禁用浏览器 CPU 节流?
- html - Safari 上的 Flexbox 错误
- svelte - 导入外部库,如 node.js 特殊语法