我使用Retrofit + OkHttp在Android应用程序中使用了API。 我正在使用gson反序列化json响应。如果发生HTTP错误,则正常的json响应将如下所示:
{
"httpStatus": 401,
"devMessage": "Invalid credentials",
"message": "Invalid credentials"
}
通常,如果遇到HTTP错误,我将从message
字段中获取错误消息,并将其显示给用户。但是,有时message
字段没有给出明确的错误消息。在data
-> fields
中的动态字段名称中提供了详细的错误消息,如下所示:
{
"httpStatus": 422,
"devMessage": "The given data was invalid.",
"message": "The given data was invalid.",
"data": {
"fields": {
"user.phone": [
"The user.phone field is required."
]
}
}
}
或
{
"httpStatus": 422,
"devMessage": "The given data was invalid.",
"message": "The given data was invalid.",
"data": {
"fields": {
"location.address": [
"The location.address field is required."
]
}
}
}
如果存在错误详细信息,我需要从该字段中获取详细消息,并将其作为清晰的错误消息显示给用户。因此,例如,在上述情况下,我将在其中显示消息
data
-> fields
-> location.address
-> ERROR MESSAGE
如何解决此问题?