简体   繁体   English

使用Jackson反序列化从JSON到POJO的消息

[英]Deserialize message from JSON to POJO using Jackson

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. 如果您不知道在不检查消息的情况下确切使用哪种类型的POJO,您将如何使用Jackson将JSON文档反序列化为POJO。 Is there a way to register a set of POJOs with Jackson so it can select one based on the message? 有没有办法向杰克逊注册一组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消息,并根据消息内容反序列化为多个POJO之一。

I'm not aware of a mechanism that you are describing. 我不知道你正在描述的机制。 I think you will have to inspect the json yourself: 我想你必须亲自检查一下json:

    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));

If you don't have a type field you will have to inspect the fields in the JsonNode in order to resolve the type. 如果您没有类型字段,则必须检查JsonNode中的字段以解析类型。

BeanDeserializer, in Jackson is deprecated. Jackson中的BeanDeserializer已被弃用。 However, I had the same problem and I solved it using Google's GSon . 但是,我遇到了同样的问题,我使用谷歌的GSon解决了它。 Have a look at this example. 看看这个例子。

Given your POJO data type: 给出您的POJO数据类型:

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}
  • Serialization 序列化

     BagOfPrimitives obj = new BagOfPrimitives(); Gson gson = new Gson(); String json = gson.toJson(obj); // ==> json is {"value1":1,"value2":"abc"} 

Note that you can not serialize objects with circular references since that will result in infinite recursion. 请注意,您无法使用循环引用序列化对象,因为这将导致无限递归。

  • Deserialization 反序列化

     BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class); 

If you have flexibility in your JSON library, take a look at Jackson . 如果您的JSON库具有灵活性,请查看Jackson It has a BeanDeserializer that can be used for this very purpose. 它有一个BeanDeserializer ,可用于此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM