【发布时间】:2021-08-24 22:08:06
【问题描述】:
我通过类似这样的 API 获取 JSON。
如您所见,第一个对象名称是一个增量值。如何使用 moshi 处理数据类或接口中的变量对象名称? 对于“普通”JSON 文件,此代码有效。有没有办法让数据类对象名可变或者如何改变接口创建常量名?
数据类:
data class PhilipsHueLightsApi(
val lightId: List<HueLight>
)
data class HueLight(
val state: HueLightState,
val swupdate: HueLightSwupdate,
val type: String,
val name: String,
val modelid: String,
val manufacturername: String,
val productname: String,
val capabilities: HueLightCapabilities,
val config: HueLightConfig,
val uniqueid: String,
val swversion: String
)
data class HueLightState (
val on: Boolean,
val bri: Int,
val hue: Int,
val sat: Int,
val effect: String,
val xy: HueLightColorCode,
val ct: Int,
val alert: String,
val colormode: String,
val mode: String,
val reachable: Boolean
)...
API 服务:
interface OpenPhilipsHueConnection {
/**
* A public interface that exposes the [getPhilipsHueLightsApi] method
*/
interface OneCallApiConnection {
/**
* The @GET annotation indicates that endpoint will be requested with the GET HTTP method
*/
@GET("/$API_GET/$USER_ID/$API_SELECTION")
suspend fun getPhilipsHueLightsApi(): Response<PhilipsHueLightsApi>
}
// Singleton
object OpenPhilipsHueLightsApi {
/**
* Build the Moshi object with Kotlin adapter factory that Retrofit will be using.
*/
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
/**
* The Retrofit object with the Moshi converter.
*/
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
val oneCallApi: OneCallApiConnection by lazy { retrofit.create(OneCallApiConnection::class.java) }
}
}
错误信息:
I/LightRepository: Failure: Required value 'lightId' missing at $
【问题讨论】:
-
不要在问题中使用代码截图,复制粘贴代码本身。
标签: json kotlin retrofit moshi