杰克逊反序列化子类型将枚举字段设置为空

时间:2019-03-11 10:39:52

标签: java enums jackson json-deserialization

更新:删除了多余的代码

我需要反序列化JSON对象,该对象可以是父类的许多子类型之一。它由哪种特定的子类型由对象中的特定枚举字段确定。我已经向父类添加了@JsonTypeInfo@JsonSubTypes注释,据我所知它们都是正确的。

但是,枚举值与Java类中的枚举名称不完全相同。因此,在枚举类中,我用@JsonCreator注释了一个静态方法,以便杰克逊知道如何将值反序列化为适当的Java枚举。

我遇到的问题是,一旦我反序列化JSON字符串,保存枚举的字段就不包含实际的枚举值,而是保留为null

为什么day字段保留为null,如何在反序列化期间按预期设置它?

下面的代码。

父日历类

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "day")
// For the sake of correct deserialisation, we need to map from values of type to child model classes explicitly
@JsonSubTypes({ @JsonSubTypes.Type(value = Monday.class, name = "monday"),
   @JsonSubTypes.Type(value = Monday.class, name = "mon"),
   @JsonSubTypes.Type(value = Tuesday.class, name = "tuesday"),
   @JsonSubTypes.Type(value = Tuesday.class, name = "tues")})
public class Calendar {
   protected String calendarName;
   protected DaysOfWeek day;

   @JsonProperty("calendarName")
   public String getCalendarName() {
      return calendarName;
   }

   public void setCalendarName(String calendarName) {
      this.calendarName = calendarName;
   }

   @JsonProperty("day")
   public DaysOfWeek getDay() {
      return day;
   }

   public void setDay(DaysOfWeek day) {
      this.day = day;
   }
}

周一和周二的儿童班 星期一

public class Monday extends Calendar {
   private NegativeFeelings object;

   public Monday() {
   }

   public Monday(NegativeFeelings object) {
      this.object = object;
   }

   @JsonProperty("object")
   public NegativeFeelings getObject() {
      return object;
   }

   public void setObject(NegativeFeelings object) {
      this.object = object;
   }
}

星期二

public class Tuesday extends Calendar {
   private Meetings object;

   public Tuesday() {
   }

   public Tuesday(Meetings object) {
      this.object = object;
   }

   @JsonProperty("object")
   public Meetings getObject() {
      return object;
   }

   public void setObject(Meetings object) {
      this.object = object;
   }
}

DaysOfWeek枚举类

public enum DaysOfWeek {
   MONDAY("monday"),
   MON("mon"),
   TUESDAY("tuesday"),
   TUES("tues");

   private String value;

   DaysOfWeek(String value) {
      this.value = value;
   }

   @Override
   @JsonValue
   public String toString() {
      return String.valueOf(value);
   }

   @JsonCreator
   public static DaysOfWeek fromEventString(@JsonProperty("value") String eventString) {
      return Arrays.stream(DaysOfWeek.values()).filter(e -> e.value.equals(eventString)).findFirst().get();
   }
}

JSON源字符串

{
  "calendarName":"My Tuesdays",
  "day":"tuesday",
  "object":{
    "meetings":[
      "team",
      "company",
      "client"]
  }
}

反序列化的对象(从字符串上方反序列化)

Tuesday {
  object=Meetings {
  meetings=[team, company, client]
},
  calendarName=My Tuesdays,
  day=null //I want this to be "tuesday", not null
}

0 个答案:

没有答案