如何使用getValue(Subclass.class)反序列化Firebase中的子类我正在使用新的firebase sdk for android并使用真正的数据库功能。当我使用getValue(simple.class)一切都很好。但是,当我想解析一个子类的类时,母类的所有属性都是null,并且我有这种类型的错误:在类uk.edume.edumeapp.TestChild上找不到名称的setter / fieldpublic 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,我得到在类uk.edume.edumeapp.TestChild上找不到motherAttribute的setter / field我解析的Json是:{
"childAttribute" : "attribute in child class",
"motherAttribute" : "attribute in mother class"}
3 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
Firebaser在这里
这是某些版本的Firebase Database SDK for Android中的已知错误:我们的序列化程序/反序列化程序仅考虑声明的类上的属性/字段。
Firebase Database SDK for Android版本9.0到9.6(iirc)中缺少基类继承属性的序列化。从那时起它被添加回版本中。
解决方法
在此期间,您可以使用Jackson(Firebase 2.x SDK在引擎盖下使用)来使继承模型工作。
更新:这里有一个如何从JSON 读取到您的内容的片段TestChild:
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()公开了,因为只考虑公共领域/吸气者。有了这个改变,这个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有点奇怪,但幸运的是它是一个可以复制/粘贴的神奇咒语。
萧十郎
TA贡献1815条经验 获得超13个赞
对于:
在类uk.edume.edumeapp.TestChild上找不到motherAttribute的setter / field
为TestChild类设置setter:
public class TestMother {
private String motherAttribute;
public String getMotherAttribute() {
return motherAttribute;
}
//set
public void setMotherAttribute(String motherAttribute) {
this.motherAttribute= motherAttribute;
}
}添加回答
举报
0/150
提交
取消
