android - Firebase 到自定义 Java 对象

标签 android firebase firebase-realtime-database

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

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

最佳答案

像往常一样,您需要一个 Java 类来将每个属性从 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://stackoverflow.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}}

关于android - Firebase 到自定义 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34882779/

相关文章:

android - Github 对 pull 请求发表评论的 TeamCity 触发器

c# - 统一 C# Firebase : What do I do if "task.Exception.Message" returns "one or more errors have occurred" and is not returning data?

java - 从 Firebase 数据库中检索计数数据

javascript - 如何计算数组中对象键的总和 - javascript

javascript - 增量 ID 并将数据推送为数字 - 谷歌 Firebase 和 React Native

android - 获取 Assets 文件夹中的 SQLite 路径

java - 如何在 Libgdx 中每秒增加时间

android - Google Play 游戏服务成就 Activity 立即结束

javascript - 如何解决这个错误 "Uncaught TypeError: inputArgs[0].match is not a function"

java - 如何在自定义 key 子项中创建子项?