By okhttp log I know I get response from remote server. But when I try to parse response I receive null! How to correct parse response from the server to get data?
My Data object:
@Parcelize
data class DataItem(
@field:SerializedName("name")
val name: String? = null,
) : Parcelable
MY Api:
interface Api {
@GET("v1/media/list/image")
suspend fun getImage(): DataItem
}
My Retrofit object:
private val httpClient = OkHttpClient
.Builder()
.protocols(listOf(Protocol.HTTP_1_1))
.addInterceptor(BearerTokenInterceptor(TOKEN))
.addInterceptor(logInterceptor())
//get api by retrofit
private val api: TVApi by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build()
retrofit.create(TVApi::class.java)
}
private fun logInterceptor() : HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
return interceptor
}
My try to parse the response:
private val scope = CoroutineScope(Dispatchers.IO)
private fun getNetworkResponse() {
scope.launch {
try {
Log.d(MY_TAG, "api: ${api.getVideo()}")
} catch (e: IOException) {
Log.e(MY_TAG, "IOException: $e")
} catch (e: HttpException) {
Log.e(MY_TAG, "HttpException: $e")
}
}
}
OKhttp log:
{"code":200,"message":"Success","data":[{"name"....}
My Log:
api: DataItem(extension=null, size=null, name=null, url=null)
2
Answers
By mistake I called DataItem object instead VideoResponse or ImageResponse
My JSON:
It parse to follow data classes:
It looks like your data class does not match the JSON structure. Gson does not report missing or unknown properties, which is why this mismatch might not be obvious.
Your JSON data suggests there should be an enclosing data class, let’s call it
Response
:And then the function in your
Api
interface should have that as return type:(Also, please check the code in your question again. The
Api
interface has a function calledgetImage
, but in your code below you callgetVideo
; and your log output shows thatDataItem
has additional properties such asextension
, which are not shown in the code of yourDataItem
class above.)