简体   繁体   English

如何忽略 API 响应中的某些字段 - Retrofit @GET

[英]How to ignore some fields in API response - Retrofit @GET

I have a get API call.我有一个 get API 电话。 and the response is like this:响应是这样的:

  {
      "id": "22222",
      "resourceUri": "ssss",
      "xxx": null,
      "xxx": [],
      "phone": "kkk",
      "email": "jjjjjj",
   }

out of all these fields, I only need the ID.在所有这些字段中,我只需要 ID。 SO, I've created a class like this:所以,我创建了一个 class 这样的:

data class ApiResponse(
    val id: String,
)

and api calls is like this:和 api 电话是这样的:

suspend fun apiCall(@Header("Authorization") authorization : String) :Response<ApiResponse>

It doesn't work and it throws an error.它不起作用并且会引发错误。 What can I do?我能做什么?

There seems to be nothing wrong for the implementation you provide.您提供的实现似乎没有任何问题。 Your ApiResponse class can have less attributes than your response JSON.您的ApiResponse class 的属性可能少于您的响应 JSON。

If possible, please further provide the Exception you encounter.如果可能,请进一步提供您遇到的异常。

I have a little example below for your reference:我在下面有一个小例子供您参考:
Main.kt

fun main(args: Array<String>) {
  val retrofit = Retrofit.Builder().baseUrl("http://localhost")
    .addConverterFactory(GsonConverterFactory.create())
    .build()
  val retromock = Retromock.Builder().retrofit(retrofit).build()

  runBlocking {
    val service = retromock.create(TestCall::class.java)
    val response = service.apiCall()
    println(response.body())
  }
}

ApiResponse.kt

data class ApiResponse(
  val id: String,
  val name: String,
  val remark: String,
) {
  override fun toString(): String {
    return "ID: $id | Name: $name | remark: $remark"
  }
}

TestCall.kt

interface TestCall {
  @Mock
  @MockResponse(body = "{\"id\":\"1\", \"name\":\"Smith\", \"age\":30, \"score\":20, \"remark\":null}")
  @GET("/")
  suspend fun apiCall() : Response<ApiResponse>
}

And the output can be printed without errors:并且 output 可以无误地打印出来:

ID: 1 | Name: Smith | remark: null

So in the above example, you can see that the returning JSON contains attributes like age , score , which are not included in ApiResponse .因此在上面的示例中,您可以看到返回的 JSON 包含agescore等属性,这些属性不包含在ApiResponse中。 So you may have to check other configuration that causes the error.因此,您可能必须检查导致错误的其他配置。

Yeah, Your API response is correct.是的,您的 API 回复是正确的。 you can create a response with the needed data only.您可以仅使用所需数据创建响应。

data class ApiResponse(
    val id: String,
)

your error may be something else please share your logcat error, it might be understood the error您的错误可能是其他原因请分享您的 logcat 错误,它可能被理解为错误

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

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