如何在这两种情况下处理改造中的数据参数。如果 success 为 false 且 data 为 null,则应用程序崩溃

How do I handle the data parameter in retrofit for both the scenarios. The app crashes if success is false and data is null

我的 API 回复:

{
    success: true,
    msg: 'Custom Success Message',
    data : [Objects]
}

如果失败,响应是:

{
    success: false,
    msg: 'Custom Error Message',
    data: null
}

我的问题是如何在改造中为这两种情况处理数据参数?

如果成功为 false 且数据为 null,则应用程序崩溃。

请检查以下代码以在获取响应时检查空条件。

call1.enqueue(new Callback<YourModelClass>()
{
    @Override
    public void onResponse (Call < YourModelClass > call, Response < YourModelClass > response){

    // this line must be write
    if (Response.body != null) {
         // try this code 
         JSONObject reader = new JSONObject("your response");
         JSONArray data = reader.getString("data"); 

         if(data!=null)
         {

          }
    }
}
}

其实改造没有选项来处理 2 种类型的响应句柄。

您可以要求您的后端开发人员发送相同类型的空数据。

关于成功案例 data:[String,String]

关于失败案例 data:[]

如果您没有使用第三方 api 或者无法联系后台人员。

这是解决这种情况的方法。

在获取结果回调时使用 trycatch 使用改造异常。使用 hasUnresolvableType

进行存档

只需找出您面临的异常。

改变你的API 如果数据为空 return
{ 成功:假, 消息:'Custom Error Message', data: [] // 这是空白数组。 }

如果数据不为空则 return { 成功:真实, 消息:'Custom Success Message', 数据:[对象] }

根据我的经验,您必须告诉 API 开发人员制作具有某种结构的 API。

两种方式:

  • 如果 data 键没有可用数据,则必须有空白数组。
  • data 如果没有可用数据,则不能存在密钥。

原因: data 键为您提供数组,改造 gson 会自动将该数据转换为您的模型 class 但是如果您将得到 null 那么它会混淆转换。

Key Point: There is no need to do logical programming by Android Developer