取自 Firebase 示例,如果我有这样的恐龙事实数据结构:
{
"lambeosaurus": {
"name": "lamby",
"work": "eat",
"dimensions": {
"height" : 2.1,
"length" : 12.5,
"weight": 5000
}
},
"stegosaurus": {
"name": "stego",
"work": "play",
"dimensions": {
"height" : 4,
"length" : 9,
"weight" : 2500
}
}
}
我如何在 Firebase 的 Android 类中表示此结构以从 DataSnapshot.getValue(DinosaurFacts.class)
进行转换?
name, work 都是用String表示的,但是类中的“dimensions”集合怎么表示呢?
另外,如何从 DataSnapshot
中获取有关高度和体重的数据值?
编辑 我可以让各个元素在快照中循环,但我试图找到如何在类结构中表示数据。
for(DataSnapshot child : dataSnapshot.getChildren()) {
Log.d("hz-key:", child.getKey().toString());
Log.d("hz-val:", child.getValue().toString());
}
最佳答案
表示此结构的 JavaBean 类是:
public static class DinosaurFacts {
String name;
String work;
Dimensions dimensions;
public String getName() {
return name;
}
public String getWork() {
return work;
}
public Dimensions getDimensions() {
return dimensions;
}
public class Dimensions {
double height;
long weight;
double length;
public double getHeight() {
return height;
}
public long getWeight() {
return weight;
}
public double getLength() {
return length;
}
}
}
然后你可以阅读恐龙:
DinosaurFacts dino = dinoSnapshot.getValue(DinosaurFacts.class);
并访问维度,例如:
dino.getDimensions().getWeight();
关于android - 如何在 Firebase 类中表示嵌套数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33010429/