0

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?

1 Answer 1

1

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>
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.