繁体   English   中英

android-kotlin JsonObject JsonArray 通过 POST 发送请求数据

[英]android-kotlin JsonObject JsonArray send request data via POST

我想通过 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" 

谢谢你

我可以从您的请求中看到的一个问题是密钥与您发送的内容不同,检查可能不同。 它应该是city而不是给定的listCity

data class CityRequest(
   @SerializedName("city")
   val city: List<City?>
)

和你的城市 class 应该有你提到的这些关键answer作为details

data class City(
   @SerializedName("cityId")
   val cityId: Int?,
   @SerializedName("answer")
   val answer: List<String?>
)

我猜您只是发送了错误的密钥,这可能是服务器不接受请求的原因。 进行上述更改,如果您遇到错误,它应该可以发布。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM