如何跳过Firestore集合中的null/empty变量? [英] How to skip null/empty variables in the firestore collection?

查看:33
本文介绍了如何跳过Firestore集合中的null/empty变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像Firebase实时数据库一样,我不希望在Firestore集合中存储null/empty值.因此,我如何从Firestore集合中跳过或删除null字段

Like firebase real-time database, I don't want store null/empty value in firestore collection .so how i can skip or remove null fields from firestore collection

以下功能将数据保存到Firestore

below function save data to firestore

private void saveTofireStore(String path, User userObject,Class<?> classType){

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    documentReference = db.document(path);
    Log.d(TAG,""+documentReference.getPath());
   documentReference
            .set(userObject)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()){
                  appearanceMutableLiveData.setValue(task.getResult());
                }else {
                    appearanceMutableLiveData.setValue(null);
                }
            });

}

推荐答案

我发现了一种使用Gson序列化对象然后转换为映射然后可以保存该对象的简单方法

I found an easy way using Gson to serialize object then convert into the map then you can save that object

private Map<String, Object> removeNullValues(User userObject) {
    Gson gson = new GsonBuilder().create();

    Map<String, Object> map = new Gson().fromJson(
            gson.toJson(userObject), new TypeToken<HashMap<String, Object>>() {
            }.getType()
    );

    return map;
}

然后

documentReference
.set( removeNullValues( userObject) )
.addOnSuccessListener {}

如果您使用的是proguard,请确保添加此规则

If you are using proguard then make sure add this rules

-keepclassmembers enum * { *; }

这篇关于如何跳过Firestore集合中的null/empty变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆