[英]Write Jackson Custom Deserializer for a particular attribute in an hierarchical JSON map
JSON Object: JSON对象:
["emp" : { "departments": [ "modules": [ { "tasks": [ { "resources": 100, "notes": "" } ] } ] ] }]
I would want to map the above JSON onto a
List<Emp>
object. 我想将上面的JSON映射到List<Emp>
对象。 My object mapper would look like: 我的对象映射器如下所示:
List<Emp> emps = Arrays.asList(mapper.readValue(jsonString, Emp[].class));
This simple object mapper works well. 这个简单的对象映射器效果很好。
My problem is I have to deserialize tasks
object from the JSON on to the Task
object in a different manner. 我的问题是我必须以不同的方式将tasks
对象从JSON反序列化到Task
对象。
I understand that we can write a custom deserializer using jackson, but that is not solving my case. 我知道我们可以使用jackson编写自定义解串器,但这不能解决我的问题。 I have written a CustomeDeserializer
for the Task
object, but registering this to the Object Mapper as follows would try to serialize the whole JSON ( List<Emp>
) as aa task object. 我已经为Task
对象编写了CustomeDeserializer
,但是按如下所示将其注册到Object Mapper会尝试将整个JSON( List<Emp>
)序列化为一个Task对象。
SimpleModule mod = new SimpleModule("MyModule"); ObjectMapper mapper = new ObjectMapper(); mod.addDeserializer(Task.class, new CustomDeserializer(Task.class)); mapper.registerModule(mod);
Is there a way to specify the CustomDeserializer
only for a particular attribute during parsing? 有没有一种方法可以在解析过程中仅为特定属性指定CustomDeserializer
? Or is there an alternative for this ? 还是为此有其他选择?
Note: I cannot change my DTO's to fix this. 注意:我无法更改DTO来解决此问题。
There are several alternatives for parsing JSON with Jackson. 使用Jackson解析JSON有几种选择。 You can use Jacksons Tree model
parsing or the streaming API
. 您可以使用Jacksons Tree model
解析或streaming API
。 Both require more code than just mapper.readValue(jsonString, Emp[].class)
but it's a lot better than implementing your own JSON parsing. 两者都需要比mapper.readValue(jsonString, Emp[].class)
更多的代码mapper.readValue(jsonString, Emp[].class)
但比实现自己的JSON解析要好得多。 You can read about them in the Jackson documentation here 您可以在Jackson文档中阅读有关它们的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.