首页 > 解决方案 > Gson 错误“声明多个名为的 JSON 字段”用于覆盖的继承字段

问题描述

我有 2 节课:

家长

class Parent {
    @SerializedName("variable1")
    int variable1;

    @SerializedName("child")
    Child child;

    //Getters and Setters
}

孩子

class Child {
    @SerializedName("childVar")
    int childVar1;

    //Getters and Setters
}

这些扩展如下:

扩展子

class ExtendedChild extends Child {
    @SerializedName("childVar2")
    int childVar2;

    //Getters and Setters
}

扩展父级

class ExtendedParent extends Parent {
    @SerializedName("variable2")
    int variable2; 

    @SerializedName("child")
    ExtendedChild extendedChild;

    //Getters and Setters
}

我想使用这些类从 Json 中取消编组。我打算使用 GSON 库。我想根据有效负载取消编组到 ExtendedParent 或 Parent 类。我在我的代码中知道它是哪种类型的 Parent。只是为了正确表示并避免冗余变量声明,我想使用继承。以下是我随身携带的两个示例-

我会将以下有效负载编组到 ExtendedParent.class

{
    'variable1':12,
    'variable2':23,
    'child':{
        'childVar1': 43,
        'childVar2': 23
    }
}

我会将以下有效负载编组到 Parent.class

{
    'variable1':12,
    'child':{
        'childVar1': 43
    }
}

但是,当我尝试按以下方式取消编组时-,

ExtendedParent extendedParent = new Gson()
        .fromJson('<Passing the first Json string above>', ExtendedParent.class);

我面临以下异常。

java.lang.IllegalArgumentException:ExtendedParent 类声明了多个名为 child 的 JSON 字段

无法弄清楚是什么问题。任何帮助或指示将不胜感激。我尝试了几种方法来避免变量隐藏在子对象上,但我无法弄清楚如何解决这个问题。

标签: javajsoninheritancegson

解决方案


GSON 不处理多次声明的具有相同名称的字段,无论它是 Java 字段名还是序列化名称。使用泛型来避免这种情况。声明你的Parent喜欢:

public class Parent<T extends Child> {
    private T child;
    // any other stuff
}

喜欢ExtendedParent

public class ExtendedParent extends Parent<ExtendedChild> {
    // note no more declaring the field "child"
    // any other stuff
}

如果您需要使用名称extendedChild,您可以为使用child.

相关问题在这里


推荐阅读