Deserialize message from JSON to POJO using Jackso

2019-07-06 19:59发布

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?

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.

3条回答
beautiful°
2楼-- · 2019-07-06 20:26

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

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

查看更多
可以哭但决不认输i
3楼-- · 2019-07-06 20:26

If you have flexibility in your JSON library, take a look at Jackson. It has a BeanDeserializer that can be used for this very purpose.

查看更多
smile是对你的礼貌
4楼-- · 2019-07-06 20:28

BeanDeserializer, in Jackson is deprecated. However, I had the same problem and I solved it using Google's GSon. Have a look at this example.

Given your POJO data type:

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);
    
查看更多
登录 后发表回答