【发布时间】:2019-03-13 11:56:16
【问题描述】:
我正在使用 Retrofit 2,我需要处理 JSON 格式的响应错误。以下是响应正文的示例。
{
"success": false,
"error": {
"message": {
"name": [
"This input is required."
]
}
}
}
message 包含有错误的字段列表,这意味着该值是动态的。因此,一种可能的解决方案是将响应正文解析为 JSON 对象。我尝试使用 response.errorBody().string()
@Override
public void onResponse(final Call<Category> call, final Response<Category> response) {
if (response.isSuccessful()) {
} else {
// Handle error
String errorBody = response.errorBody().string();
}
}
不幸的是,打印errorBody我只能得到以下结果
{"success":false,"error":{"message":{"name":[""]}}}
Retrofit 是否限制了 errorBody 对象的深度?我应该怎么做才能得到可以解析的完整响应体?
【问题讨论】:
-
试试这样写:String errorBody = response.errorBody().string(); if true 语句中的 else 之前。
-
@UmangBurman 为什么要在此处添加
response.errorBody().string();?如果响应为 4xx,则不会通过 if true 块 -
@NoName2 你解决了吗?我有完全相同的问题。
-
解决方案在这里https://stackoverflow.com/a/70135493/4882029 它对我来说很好。
标签: android retrofit retrofit2