使用Gson反序列化动态API响应

时间:2019-09-24 00:23:32

标签: android gson retrofit okhttp json-deserialization

我使用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

如何解决此问题?

0 个答案:

没有答案