【问题标题】:Gson error "declares multiple JSON fields named" for overridden inherited fieldsGson 错误“声明多个名为的 JSON 字段”用于覆盖的继承字段
【发布时间】:2019-04-08 12:18:19
【问题描述】:

我有 2 节课:

父母

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

    @SerializedName("child")
    Child child;

    //Getters and Setters
}

儿童

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

    //Getters and Setters
}

这些扩展如下:

ExtendedChild

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

    //Getters and Setters
}

ExtendedParent

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 字段

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

【问题讨论】:

    标签: java json inheritance gson


    【解决方案1】:

    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,您可以为该名称创建 getter 和 setter 以处理 child

    相关问题here

    【讨论】:

    • 太棒了,确实有效。感谢您的见解。此解决方案快速而简洁。
    猜你喜欢
    • 2019-08-23
    • 2016-01-25
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2019-03-24
    • 2014-09-09
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多