Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

How do I declare an array of json in kotlin

I'm a beginner with kotlin and Android Studio and I'm trying to declare a json array in a data class. 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.

Here is my Json:

{
_id : String,
name : String,
type : String,
  stateList : [{
  date: Integer,
  source : String,
  variables:[{
    name: String,
    value: String,
        }]
    }]
}

and here is my attempt:

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)

I guess that this is not the good way to declare my Json so what is the proper way to do it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you should change class State to something like this (match variable name with json atribute name):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...