java - 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 字段
无法弄清楚是什么问题。任何帮助或指示将不胜感激。我尝试了几种方法来避免变量隐藏在子对象上,但我无法弄清楚如何解决这个问题。
解决方案
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
.
相关问题在这里。
推荐阅读
- python - 如何根据条件过滤熊猫系列值
- python - 带有简单代理类的 RecursionError
- wordpress - 仅向来自 CA 的客户添加捐赠复选框
- java - 使用Jackson反序列化JSON实体的动态属性
- r - 为 R 中的 data.frame 中的每个“id”单独但唯一地创建一个变量
- reactjs - 打字稿三元表达式错误说条件将始终返回“假”
- ios - 在标签栏控制器中嵌入“显示”序列
- google-analytics - 向 Google Analytics 发送虚拟页面视图时动态设置页面值
- math - 归一化向量函数返回意外结果
- html - CSS:带有弯曲边缘和居中文本(水平和垂直居中)