[英]How to write flattening List deserializer with Jackson?
I'm trying to deserialize JSONs of specific structure into Java classes with Jackson. 我正在尝试使用Jackson将特定结构的JSON反序列化为Java类。 I have several classes like these:
我有几个像这样的课程:
class A {
private int number1;
private List<X> list1;
private int number2;
}
class X {
private String field1;
private double value1;
}
class B {
private String name2;
private List<Y> list2;
}
class Y {
private String field2;
}
And I get JSONs from external system like below: 我从外部系统获取JSON,如下所示:
{
"number1": 1,
"list1": {
"elements": [{
"field1": "Field 1 value 1",
"value1": 2.2
}, {
"field1": "Field 1 value 2"
}]
},
"number2": 2,
}
{
"name2": "Name 2",
"list2": {
"elements": [{
"field2": "Field 2 value 1"
}]
}
}
All I want is to write a custom deserializer, which could get rid of this elements level in a generic way (I mean to have one deserializer for all classes). 我只想编写一个自定义反序列化器,可以以一种通用的方式摆脱这个元素级别(我的意思是为所有类都拥有一个反序列化器)。 Is there any simple way to extend a StdDeserializer to accomplish that or a I have to write a whole new deserializer with my custom algorithm?
有没有简单的方法来扩展StdDeserializer来完成该任务,或者我必须使用自定义算法编写一个全新的反序列化器?
You can take a look on this question: Jackson - deserialize inner list of objects to list of one higher level which is very similar. 您可以看一下这个问题: Jackson-将内部对象列表反序列化为非常相似的更高级别的列表 。 I have implemented there custom deserialiser which can be used for many different types with inner list.
我已经实现了自定义反序列化器,该反序列化器可用于带有内部列表的许多不同类型。 Your example
POJO
could look like this: 您的示例
POJO
可能如下所示:
class A {
private int number1;
@JsonDeserialize(using = InnerListDeserializer.class)
private List<X> list1;
private int number2;
// getters, setters
}
EDIT 编辑
If you do not want to use any annotation or custom deserialisation you need to create POJO
structure which fit given JSON
. 如果您不想使用任何注释或自定义反序列化,则需要创建适合给定
JSON
POJO
结构。 You need to create middle POJO
: 您需要创建中间
POJO
:
class ListWrapper<T> {
private List<T> elements;
// getter, setter, toString, etc
}
Now, you need to update classes A
and B
in this way: 现在,您需要以这种方式更新类
A
和B
:
class A {
private int number1;
private ListWrapper<X> list1;
private int number2;
// getters, setters, toString
}
and 和
class B {
private String name2;
private ListWrapper<Y> list2;
// getters, setters, toString
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.