I'm having the weirdest bug I EVER had.
For a school project, I need to get the JSON of this API. I didn't encounter any error, but the response body is null. Not exactly null, but still null. First, here is the code I use to get the data (Yeah, it's in the UI thread but this is not my main problem)
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("http://barcelonaapi.marcpous.com")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
val service = retrofit.create(StationAPI::class.java)
val call = service.stationsList()
call.enqueue(object : Callback<StationResponse> {
override fun onResponse(
call: Call<StationResponse>,
response: Response<StationResponse>
) {
val statusCode: Int = response.code()
val resp: StationResponse? = response.body()
Log.d("JSON", "Status code: $statusCode")
Log.d("JSON", "Resp: $resp")
}
override fun onFailure(call: Call<StationResponse>?, t: Throwable) {
t.printStackTrace()
}
})
And here is my data classes:
interface StationAPI {
@GET("/bus/nearstation/latlon/41.3985182/2.1917991/1.json")
fun stationsList(): Call<StationResponse>
}
data class StationResponse (
@field:Json(name = "code") var code: Int,
@field:Json(name = "data") var data: NearStation
)
data class NearStation(
@field:Json(name = "nearstations") var stations: List<Station>
)
data class Station(
@field:Json(name = "id") var id: Long,
@field:Json(name = "street_name") var streetName: String?,
@field:Json(name = "city") var city: String?,
@field:Json(name = "utm_x") var utmX: String?,
@field:Json(name = "utm_y") var utmY: String?,
@field:Json(name = "lat") var latitude: String?,
@field:Json(name = "lon") var longitude: String?,
@field:Json(name = "furniture") var furniture: String?,
@field:Json(name = "buses") var buses: String?,
@field:Json(name = "distance") var distance: Float,
)
In onResponse(), the response code is always equal to 0 (default value for Int) and data is always null. BUT, now the fun begins. If I comment @field:Json(name = "data") var data: NearStation
, the code parameter is now 200 as it should be.
And to add more fun to the fun cake, a friend has exactly the same code but it's working for him.
Please help, I don't understand.
question from:
https://stackoverflow.com/questions/65648395/retrofit-mochi-empty-response-and-weird-bug 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…