假设我有数据类:
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"
...
}
}
}
}
}
谢谢!
答案 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}}