如何知道Firestore文档中每个属性的类型?

huangapple go评论94阅读模式
英文:

How to know the type of each property in a Firestore document?

问题

以下是您要翻译的内容:

我有这个数据库:

root
 \_ users
     \_ uid
         \_ name:“Pathis”
         \_ admin:true
     \_ uid
         \_ name:“Venkat”
         \_ admin:false

获取数据的代码:

db.collection("users").whereEqualTo("admin", true).get().addOnCompleteListener(task -> {
    if (task.isSuccessful()) {
        for (QueryDocumentSnapshot document : task.getResult()) {
            boolean admin = document.getBoolean("admin");
        }
    }
});

这可以工作,因为我知道类型(name 是 String,admin 是 boolean)。但如果我不知道它们,该怎么办?我需要一种获取文档并验证每个属性的方法。假设我找到了 name,我想要验证为 String 类型,我找到了 admin,应该是 boolean。是否有解决方案?

英文:

I have this db:

root
 \_ users
     \_ uid
         \_ name: "Pathis"
         \_ admin: true
     \_ uid
         \_ name: "Venkat"
         \_ admin: false

Code to get the data:

db.collection("users").whereEqualTo("admin", true).get().addOnCompleteListener(task -> {
    if (task.isSuccessful()) {
        for (QueryDocumentSnapshot document : task.getResult()) {
            boolean admin = document.getBoolean("admin");
        }
    }
});

It works because I know the types (name is a String, admin is a boolean). But how would this work if I did not know them? What I need is a way to get the document and verify each property. Let's say I find name and I would like to verify as String type, I find admin and I should get boolean. Is there a solution for this?

答案1

得分: 1

如果您事先不知道值的类型,您将不得不使用get()方法将值作为Object访问,然后使用Java的instanceof运算符检查其类型。例如:

Object adminObject = document.get("admin");
if (adminObject instanceof String) {
    String admin = (String) adminObject;
}
else if (adminObject instanceof Boolean) {
    boolean admin = (Boolean) adminObject;
}

这并不是详尽的方法,只是一个简短的示例。您可能需要处理许多其他类型,并且您的代码可能需要适应。

英文:

If you don't know the type of value ahead of time, you will have to access the value as an Object using get(), then check its type using the Java instanceof operator. For example:

Object adminObject = document.get("admin");
if (adminObject instanceof String) {
    String admin = (String) adminObject;
}
else if (adminObject instanceof Boolean) {
    boolean admin = (Boolean) adminObject;
}

This is not an exhaustive approach - just a short example. You might need to handle many other types, and your code might need to adapt.

huangapple
  • 本文由 发表于 2020年4月7日 00:00:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/61063913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定