我想通过post向服务器发送数据请求我想知道如何在数组中添加数据
data class City(
@SerializedName("cityId")
val cityId: Int?,
@SerializedName("detail")
val detail: List<String?>
)
请求
data class CityRequest(
@SerializedName("listCity")
val listCity: List<City?>
)
响应
data class CityResponse(
@SerializedName("code")
val code: String?,
@SerializedName("status")
val status: Boolean?,
@SerializedName("message")
val message: String?
)
API服务器
@Headers("Content-Type: application/json")
@POST("city")
suspend fun sendCityContent(@Body listCity: CityRequest?):
Call<CityResponse?>
连接服务我不知道如何将信息添加到有问题的部分。
private suspend fun sendDataCity(city: List<city?>) {
val retrofit = clientCity
val sendDataToServer = retrofit?.create(CityService::class.java)
val call = sendDataToServer?.sendCityContent(CityRequest(city))
call?.enqueue(object : Callback<CityResponse?> {
override fun onResponse(
call: Call<CityResponse?>, response: Response<CityResponse?>) {
val getResponse = response.body()
Timber.tag("SALE_CITY: ").d("code: %s", getResponse?.code)
Timber.tag("SALE_CITY: ").d("status: %s", getResponse?.status)
Timber.tag("SALE_CITY: ").d("message: %s", getResponse?.message)
}
override fun onFailure(call: Call<CityResponse?>, t: Throwable?) {
t?.printStackTrace()
}
})
}
JSON简单
{
"city": [
{
"cityId": 1,
"answer": [
"1"
]
},
{
"questionId": 2,
"answer": [
"2.1",
"2.2"
]
}
]}
我下一步该怎么办?你能给我一个在数组中添加数据的例子吗?我想要的东西
cityId = 1
detail = "1.1", "1.2"
cityId = 2
detail = "2.1", "2.2"
谢谢
我在您的请求中看到的一个问题是,密钥与您发送的密钥不同,请检查。它应该是CCD_ 1而不是给定的CCD_。
data class CityRequest(
@SerializedName("city")
val city: List<City?>
)
你的城市类应该有这些密钥answer
,你提到的是details
data class City(
@SerializedName("cityId")
val cityId: Int?,
@SerializedName("answer")
val answer: List<String?>
)
我想你只是用错误的密钥发送,这可能是服务器不接受请求的原因。做上面的改变,如果你得到错误,它应该工作后。