我正在为 Android 使用新的 firebase sdk 并使用真正的数据库功能。当我使用 getValue(simple.class)
时,一切都很好。但是当我要解析一个子类的类时,母类的所有属性都是null
,我有这样的错误:
No setter/field for name found on class uk.edume.edumeapp.TestChild
public class TestChild extends TestMother {
private String childAttribute;
public String getChildAttribute() {
return childAttribute;
}
}
public class TestMother {
protected String motherAttribute;
protected String getMotherAttribute() {
return motherAttribute;
}
}
这个函数
snapshot.getValue(TestChild.class);
motherAttribute
属性为 null
,我得到 p>
No setter/field for motherAttribute found on class uk.edume.edumeapp.TestChild
我解析的 Json 是:
{
"childAttribute" : "attribute in child class",
"motherAttribute" : "attribute in mother class"
}
最佳答案
这里是 Firebaser
这是 Android 版 Firebase 数据库 SDK 某些版本中的一个已知错误:我们的序列化器/反序列化器仅考虑已声明类的属性/字段。
Android 版 Firebase 数据库 SDK 9.0 至 9.6 (iirc) 版中缺少从基类继承的属性的序列化。从那时起,它又被添加回了版本。
解决方法
与此同时,您可以使用 Jackson(Firebase 2.x SDK 在后台使用)使继承模型正常工作。
更新:这是您如何将从 JSON 读取到您的 TestChild
中的 fragment :
public class TestParent {
protected String parentAttribute;
public String getParentAttribute() {
return parentAttribute;
}
}
public class TestChild extends TestParent {
private String childAttribute;
public String getChildAttribute() {
return childAttribute;
}
}
您会注意到我将 getParentAttribute()
公开,因为只考虑公共(public)字段/getter。有了这个改变,这个 JSON:
{
"childAttribute" : "child",
"parentAttribute" : "parent"
}
变得可读:
ObjectMapper mapper = new ObjectMapper();
GenericTypeIndicator<Map<String,Object>> indicator = new GenericTypeIndicator<Map<String, Object>>() {};
TestChild value = mapper.convertValue(dataSnapshot.getValue(indicator), TestChild.class);
GenericTypeIndicator
有点奇怪,但幸运的是它是一个可以复制/粘贴的魔法咒语。
关于java - 如何使用 getValue(Subclass.class) 在 Firebase 中反序列化子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37547399/