Firebase 到自定义 Java 对象

Firebase to custom Java object

{
  "users": {
    "mchen": {
      "friends": { "brinchen": true },
      "name": "Mary Chen",
      "widgets": { "one": true, "three": true }
    },
    "brinchen": { ... },
    "hmadi": { ... }
  }
}

如何为上面的例子编写自定义对象class? Firebase 中的指南仅显示简单示例。

像往常一样,您需要一个 Java class 将每个 属性 从 JSON 映射到一个字段+getter:

static class User {
    String name;
    Map<String, Boolean> friends;
    Map<String, Boolean> widgets;

    public User() { }

    public String getName() { return name; }
    public Map<String, Boolean> getFriends() { return friends; }
    public Map<String, Boolean> getWidgets() { return widgets; }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", friends=" + friends +
                ", widgets=" + widgets +
                '}';
    }
}

我真的只是按照 Firebase guide on reading data on Android 中的这些说明操作:

We'll create a Java class that represents a Blog Post. Like last time, we have to make sure that our field names match the names of the properties in the Firebase database and give the class a default, parameterless constructor.

然后你可以这样加载信息:

Firebase ref = new Firebase("https://Whosebug.firebaseio.com/34882779/users");
ref.addListenerForSingleValueEvent(new ValueEventListenerBase() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            System.out.println(userSnapshot.getKey()+": "+userSnapshot.getValue(User.class));
        }
    }
});

有了这个输出:

brinchen: User{name='Brin Chen', friends={mchen=true, hmadi=true}, widgets={one=true, three=true, two=true}}

hmadi: User{name='Horace Madi', friends={brinchen=true}, widgets={one=true, two=true}}

mchen: User{name='Mary Chen', friends={brinchen=true}, widgets={one=true, three=true}}