问题
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
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);
}
});
}
回答1:
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;
}
and then
documentReference
.set( removeNullValues( userObject) )
.addOnSuccessListener {}
来源:https://stackoverflow.com/questions/51216441/how-to-skip-null-empty-variables-in-the-firestore-collection