jackson 反序列化到其字段应根据运行时反序列化对象

rqqzpn5f  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(144)

我有一个类像下面,

class KafkaJsonWrapper{

String version;
Object kafkaEvent;

}

当我序列化这个对象时,我传递了来自不同服务的kafkaEvent,数据模型也不同。
例如,

KafkaJsonWrapper obj = ..
obj.setKafkaEvent(new AccountEvent()) 
obj.setKafkaEvent(new BonusTriggeredEvent()) //OR
etc..
objectMapper.writeValueAsBytes(object)

然而,当我反序列化它,我怎么能反序列化到我用于序列化的类型。

ACTUAL:
    KafkaJsonWrapper wrapper = objectMapper.readValue(buffer.array(), start, length, type); //type is KafkaJsonWrapper
    wrapper.getKafkaEvent()// inside this KafkaJsonWrapper is LinkedHashMap all the time.
    EXPECTED:
    KafkaJsonWrapper wrapper = objectMapper.readValue(buffer.array(), start, length, type); 
    wrapper.getKafkaEvent() // should be the type when it was serialzed like BonusTriggeredEvent etc.
14ifxucb

14ifxucb1#

使用子类型
范例

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
      include = As.PROPERTY, property = "type") @JsonSubTypes({

      @JsonSubTypes.Type(value = Square.class, name = "square"),
      @JsonSubTypes.Type(value = Circle.class, name = "circle")
   })
   static class Shape {
      public String name;    
      Shape(String name) {
         this.name = name;
      }
   }

   @JsonTypeName("square")
   static class Square extends Shape {
      public double length;
      Square(){
         this(null,0.0);
      }
      Square(String name, double length){
         super(name);
         this.length = length;
      }
   }

   @JsonTypeName("circle")
   static class Circle extends Shape {
     ...

反序列化程序应该只需要类类型,而不需要开始/结束位置

相关问题