java - 如何使用 getValue(Subclass.class) 在 Firebase 中反序列化子类

标签 java android jackson firebase-realtime-database json-deserialization

我正在为 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,我得到

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/

相关文章:

java - getMax 方法获取更大的数字

java - 如何将 Java 9 '--permit-illegal-access' 标志传递给 Webstart 应用程序?

java - 无法处理 jackson 中复合键的托管/反向引用 'defaultreference'

java - 使用 Jackson json 跳过一层抽象

android - 单击收藏夹按钮时更新 ListView

java - 使用 Jackson 反序列化为自定义对象的 HashMap

java - 将 Java 加密算法移植到 C++ OpenSSL

java - 实用程序类的静态成员(null)生命周期

android - 无法在支持库 EditTextPreference 上设置单行

android - 如何从 android 设备获取 android 应用程序 traces.txt 文件