Firebase:检索实现Map <k,v =“”>的类的值

时间:2017-06-22 10:16:50

标签: java android firebase firebase-realtime-database hashmap

假设我有数据类:

class MyDataClass {
    ...
    public Map<String, Object> properties = HashMap()
}

// later
MyDataClass data = snapshot.getValue(MyDataClass.class);

运行此代码后,data.properties包含给定快照中properties项下存在的所有数据。

出于某种原因,我想将properties字段的类型更改为我的自定义Map实现:

class MyMap implements Map<String, Object> { ... }

class MyDataClass {
    ...
    public MyMap properties = MyMap()
}

// later
MyDataClass data = snapshot.getValue(MyDataClass.class);

运行此代码后,data.properties没有数据。

我想知道是否有可能将数据检索到自定义地图实现?

UPD:JSON我尝试阅读

{
  items: {
    "id": {
      "name": "name",
      "properties": {
        "simpleProp1": "value1",
        "simpleProp2": "value2",
        "simpleProp3": "value3",
        "complexProp1": {
          "subPop1": "subVal1"
          ...
        }
      }
    }
  }
}

谢谢!

2 个答案:

答案 0 :(得分:2)

我认为Firebase无法直接使用您的自定义Map实施。因此,您可以考虑添加一个简单的数据类:

class MyDataJSON {
    public MyDataJSON() { }
    public String name;
    public Map<String, Object> properties;
}

class MyDataClass {
    MyDataClass(MyDataJSON json) { ... }
    ...
}

然后用它来构建你的MyDataClass对象:

MyDataJSON json = snapshot.getValue(MyDataJSON.class);
MyDataClass data = MyDataClass(json);

我知道,远非完美,但至少您可以完全控制数据库解组进程(以及相应的属性类型)。

答案 1 :(得分:0)

此代码似乎对我有用:

public static class MyDataClass {
    public String name;
    public Map<String,Object> properties = new HashMap<String,Object>();

    @Override
    public String toString() {
        return "MyDataClass{" +
                "name='" + name + '\'' +
                ", properties=" + properties +
                '}';
    }
}

然后:

    ref.addListenerForSingleValueEvent(
            new ValueEventListener() {
               @Override
               public void onDataChange(DataSnapshot dataSnapshot) {
                   MyDataClass data = dataSnapshot.getValue(MyDataClass.class);
                   System.out.println(data);
               }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    throw databaseError.toException();
                }
            });

打印:

  

MyDataClass {name =&#39; name&#39;,properties = {simpleProp2 = value2,simpleProp1 = value1,complexProp1 = {subPop1 = subVal1},simpleProp3 = value3}}