在firebase和java中,如何正确地从datasnapshot获取价值?

t0ybt7op  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(344)

最近,我在android应用程序中使用firebase,并尝试使用nosql数据结构,但遇到了一些问题。
首先,我的数据结构非常简单:

{
  "user": {
     "userid1" :{
          "id: "userid1"
          "name": "Samantha",
          "age": 25
          "email" : "abc@gmail.com"
                }     
          }
}

所以我这样写了我的实体类

public class User implements Serializable {
    private String id;
    private String name;
    private int age;
    private String email;
}

当我想让所有用户进入列表时:

FirebaseDatabase.getInstance().getReference("user").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                    for(DataSnapshot dataSnapshot : snapshot.getChildren()){
                        User user = dataSnapshot.getValue(User.class);
                        listUser.add(user);
                    }
                }
            }

但是如果我想像这样改变我的数据结构,我不知道怎么做:

{
      user: {
         userid1 :{
              id: "userid1"
              name: "Samantha",
              age: 25
              email : "abc@gmail.com"
              posts:{
                 postid1: {
                     postid  : "postid1"
                     content : "content1" 
                          }
                 postid2: {
                     postid  : "postid2"
                     content : "content2" 
                          }
                      }
                    }     
              }
    }

我想我必须创建一个post实体类,但是如何像以前一样获取用户列表呢?任何人能向我解释都会有帮助。

pieyvz9o

pieyvz9o1#

像您想做的那样嵌套数据是firebase中的一种反模式,与数据结构文档中的建议背道而驰。看到了吗https://firebase.google.com/docs/database/android/structure-data#best_practices_for_data_structure
也就是说:如果你有这样一个结构,你可以通过添加 posts Map到类以读取其数据:

public class User implements Serializable {
    public String id;
    public String name;
    public int age;
    public String email;
    public Map<String, Object> posts;
}

如果您想让他们安全地键入,您可能需要使用 GenericTypeIndicator .

相关问题