如何在 Firebase 类中表示嵌套数据 [英] How to represent nested data in Firebase class

查看:19
本文介绍了如何在 Firebase 类中表示嵌套数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取自 Firebase 示例,如果我有这样的恐龙事实数据结构:

Taken from the Firebase example, if I have a Dinosaurs facts data structure like this:

{
  "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) 进行转换?

How can I represent this structure in a Android Class for Firebase to cast from DataSnapshot.getValue(DinosaurFacts.class)?

name、work 用Strings表示,但是如何在class中表示dimensions"集合呢?

name, and work are represented as Strings, but how to represent "dimensions" collection in the class?

另外,我如何从 DataSnapshot 访问关于高度和的数据值?重量?

Also how can I access data values from DataSnapshot about height & weight?

编辑我可以让各个元素循环遍历快照,但我正在尝试找到如何在类结构中表示数据.

EDIT I can get the individual elements looping through the snapshot, but am trying to find how to represent the data in the class structure.

for(DataSnapshot child : dataSnapshot.getChildren()) {

                Log.d("hz-key:", child.getKey().toString());
                Log.d("hz-val:", child.getValue().toString());
            }

推荐答案

表示这个结构的 JavaBean 类是:

The JavaBean class to represent this structure is:

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;
        }
    }
}

然后您可以使用以下命令阅读恐龙:

Then you can read a dino with:

DinosaurFacts dino = dinoSnapshot.getValue(DinosaurFacts.class);

并访问维度,例如:

dino.getDimensions().getWeight();

这篇关于如何在 Firebase 类中表示嵌套数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆