Retrofit2 Kotlin获取Response Body异常:无法正确解析响应内容
问题排查与修复方案
核心错误:未使用接口返回的响应对象
你在onResponse方法里犯了一个基础错误:新建了一个空的LoginResponse对象printed来打印,而不是使用Retrofit已经解析好的responseFromAPI。这就是为什么你看到的都是默认值(空字符串、0),而不是后端返回的真实数据。
修正后的MainActivity关键代码
call.enqueue(object : Callback<LoginResponse> { override fun onResponse(call: Call<LoginResponse?>, response: Response<LoginResponse?>) { if (response.isSuccessful && response.body() != null) { val responseFromAPI = response.body()!! // 直接使用接口返回的解析好的对象 Log.i(TAG, "response string1 = ${responseFromAPI.smth1}") Log.i(TAG, "response string2 = ${responseFromAPI.smth2}") Log.i(TAG, "response int1 = ${responseFromAPI.smth3}") // 直接打印对象(需重写toString方法才能看到字段值) Log.i(TAG, "完整响应对象: $responseFromAPI") } else { Log.i(TAG, "请求失败或响应体为空,响应码: ${response.code()}") } } override fun onFailure(call: Call<LoginResponse?>, t: Throwable) { responseTV?.text = "Error found is : " + t.message } })
额外优化建议
- 给LoginResponse重写toString方法:直接打印对象时能看到字段值,而非内存地址
class LoginResponse ( @SerializedName("smth1") var smth1: String = "", @SerializedName("smth2") val smth2: String = "", @SerializedName("smth3") val smth3: Int = 0 ) { override fun toString(): String { return "LoginResponse(smth1='$smth1', smth2='$smth2', smth3=$smth3)" } }
- DataModal字段序列化优化:确保Gson能正确序列化密码字段,若后端参数名与本地字段名一致,可添加
@SerializedName明确映射
class DataModal { @SerializedName("password") val password = "123" }
清理冗余代码:
RetrofitAPI接口中定义的val token: String未被使用,建议删除或在请求中合理利用(如放在请求头)完善响应判断逻辑:增加
response.isSuccessful判断(响应码200-299),能排查非200段的响应问题
验证方法
修正后重新运行,查看Logcat输出,若仍有问题:
- 确认后端返回的JSON字段名与
LoginResponse的@SerializedName完全匹配(大小写敏感) - 打印原始响应字符串验证格式:
Log.i(TAG, "原始响应内容: ${response.raw().body()?.string()}")
内容的提问来源于stack exchange,提问作者Helpred
相关产品推荐
相关产品推荐

