我正在尝试使用改造和 moshi 解析换行符分隔的 json。这是我的 GET 函数:
suspend fun getDeviceValuesNew(@Path("application-id") applicationId: String, @Path("device-id") deviceId: String)
: Response<List<ValueApiResponse>>
当我尝试运行它时,我收到此错误:
com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $
HTTP 调用返回 json,如下所示:
{
"result": {
"end_device_ids": {
"device_id": "esp32",
"application_ids": {}
},
"received_at": "2021-03-31T11:33:42.757281753Z",
"uplink_message": {
"decoded_payload": {
"brightness": 0
},
"settings": {
"data_rate": {}
},
"received_at": "2021-03-31T11:33:42.547285090Z"
}
}
}
{
"result": {
"end_device_ids": {
"device_id": "esp32",
"application_ids": {}
},
"received_at": "2021-03-31T11:18:17.745921472Z",
"uplink_message": {
"decoded_payload": {
"brightness": 0
},
"settings": {
"data_rate": {}
},
"received_at": "2021-03-31T11:18:17.538276218Z"
}
}
}
编辑#1: 正如您在下面的回答中看到的,我设法从 API 获得了有效的 JSON 响应,但我仍然在努力将这些 JSON 对象解析为 Kotlin 对象列表。如何让 Moshi 将这些换行符分隔的 JSON 对象作为列表处理?我认为问题在于 Moshi 要求将对象包装在数组中才能被识别为列表。我怎么做?
这是我用于解析的数据类:
@JsonClass(generateAdapter = true)
data class ValueDto(
@Json(name = "result")
val result: Result
) {
@JsonClass(generateAdapter = true)
data class Result(
@Json(name = "end_device_ids")
val endDeviceIds: EndDeviceIds,
@Json(name = "received_at")
val receivedAt: String,
@Json(name = "uplink_message")
val uplinkMessage: UplinkMessage
) {
@JsonClass(generateAdapter = true)
data class EndDeviceIds(
@Json(name = "application_ids")
val applicationIds: ApplicationIds,
@Json(name = "device_id")
val deviceId: String
) {
@JsonClass(generateAdapter = true)
class ApplicationIds(
)
}
@JsonClass(generateAdapter = true)
data class UplinkMessage(
@Json(name = "decoded_payload")
val decodedPayload: DecodedPayload,
@Json(name = "received_at")
val receivedAt: String,
@Json(name = "settings")
val settings: Settings
) {
@JsonClass(generateAdapter = true)
data class DecodedPayload(
@Json(name = "brightness")
val brightness: Int
)
@JsonClass(generateAdapter = true)
data class Settings(
@Json(name = "data_rate")
val dataRate: DataRate
) {
@JsonClass(generateAdapter = true)
class DataRate(
)
}
}
}
}