首页 > 解决方案 > 如何在 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 的好方法,那么正确的方法是什么?

标签: arraysjsonkotlin

解决方案


我认为您应该将类​​更改State为这样的(将变量名称与 json 属性名称匹配):

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

推荐阅读