gpt4 book ai didi

android - Firebase 到自定义 Java 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:27 24 4
gpt4 key购买 nike

{
"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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com