繁体   English   中英

如何在 kotlin 中声明 json 数组

[英]How do I declare an array of json in kotlin

我是 kotlin 和 Android Studio 的初学者,我正在尝试在数据 ZA2F2ED4F198EBC2CAB1DDC20 中声明一个 json 数组。 This class is used to store data that I get from my api, but the Json is a bit complex and I dont know how to declare an array of Json with moshi.

这是我的 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 的好方法,那么正确的方法是什么?

我认为您应该将 class State更改为类似的内容(将变量名称与 json 属性名称匹配):

class State(
    @Json(name = "date") val date: Integer,
    @Json(name = "source") val source: String,
    val variables: List<variable>
)

暂无
暂无

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

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