Android:表示一个接口的所有字段都是@Nullable

Android: denote that all fields of an interface are @Nullable

我正在使用 Retrofit 从 REST API 加载数据。

我知道这个 API 有时会 return 部分结果:某些字段有时会丢失。

为了确保我正确处理这些情况,我目前在定义 API:

的界面中用 @Nullable 注释字段
class RedactedForecast implements Serializable {
    @Nullable String date;
    @Nullable String time;
    @Nullable String overview_title;
    @Nullable String overview;
    @Nullable String forecast_title;
    @Nullable String forecast;
}

然而,由于结果对象很复杂,因此在任何地方都添加此注释并不方便。

有没有办法说 class 中的所有字段都可能为空?有没有更好的方法来处理这个问题?

However adding this annotation everywhere is not convenient since the result objects are complex.

解耦结构并将数据映射到部分对象,以便于开发。

不幸的是,没有简单的方法来注释整个 class,它将特定注释应用于其所有字段。

如果您仍然依赖此解决方案,我建议您查看库 Javassist, which provides a solution for this. Here 是使用示例作为实际存在问题的答案。

在收到数据时的响应中,然后将其存储在数组列表中,例如:

ArrayList vList=response.body();

在这里,所有的数据都存储在vList对象中。

现在在这个 activity 中创建如下函数:

public ArrayList getVideosPlz() {

    ArrayList<RedactedForecast> videos = new ArrayList<>();
    try {
        for (int i = 0; i <vList.size() ; i++) {
            RedactedForecast users1=new RedactedForecast();
            String id=vList.get(i).getId();
            if(id!=null)
            {
            users1.setId(id);
            }
            videos.add(users1);
        }
    } catch (Exception e) {
        Toast.makeText(MainActivity.this, "Sorry Server Down. Try again!!!", Toast.LENGTH_SHORT).show();
    }
    return videos;
}

在上面的函数中你可以看到,只有当数据!=null时,数据才会被设置到一个名为video的新数组中,最后当所有数据都接收到时,这个"videos"对象return 并在改造 onResponse 中接收为:

ArrayList receiveData=getVideosplz();

最后,您可以将此 receiveData 传递到您的 recyclerview 等

希望对您有所帮助。谢谢!!!

更好的解决方案是使用 Kotlin,这样可以更轻松地安全处理 nulls。