使用Jackson将消息从JSON反序列化到POJO [英] Deserialize message from JSON to POJO using Jackson

查看:239
本文介绍了使用Jackson将消息从JSON反序列化到POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您不知道在不检查消息的情况下确切使用什么类型的POJO,您将如何使用Jackson将JSON文档反序列化为POJO。有没有办法向杰克逊注册一组POJO,以便根据消息选择一个?

How would you deserialize a JSON document to a POJO using Jackson if you didn't know exactly what type of POJO to use without inspecting the message. Is there a way to register a set of POJOs with Jackson so it can select one based on the message?

我正在尝试解决的方案是接收JSON消息根据消息内容对多个POJO中的一个进行连线和反序列化。

The scenario I'm trying to solve is receiving JSON messages over the wire and deserializing to one of several POJOs based on the content of the message.

推荐答案

我不知道一个机制你在描述。
我认为你必须自己检查json:

I'm not aware of a mechanism that you are describing. I think you will have to inspect the json yourself:

    Map<String, Class<?>> myTypes = ... 
    String json = ...
    JsonNode node = mapper.readTree(json);
    String type = node.get("type").getTextValue();
    Object myobject = mapper.readValue(json, myTypes.get(type));

如果您没有类型字段,则必须按顺序检查JsonNode中的字段解决类型。

If you don't have a type field you will have to inspect the fields in the JsonNode in order to resolve the type.

这篇关于使用Jackson将消息从JSON反序列化到POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆