使用Jackson的@JsonTypeInfo反序列化时,如何保留type属性?

Ole*_*Ole 3 java polymorphism json jackson deserialization

我有这样的设置:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "dishName", defaultImpl = Food.class)
@JsonSubTypes(value = {
    @Type(name = "fries", value = Fries.class),
    @Type(name = "burger", value = Burger.class)
})
public class Food {
  private String dishName;

  @Override
  public String toString() {
    return dishName + ", type: " + this.getClass().getName();
  }
}

public class Fries extends Food { /*...*/ }

public class Burger extends Food { /*...*/ }

public class TryItOut {

  private static String foodString = "[ { \"dishName\":\"burger\" }, { \"dishName\":\"fries\" }, { \"dishName\":\"cabbage\" } ]";

  public static void main(String[] args) {
    ObjectMapper m = new ObjectMapper();
    try {
        Food[] food = m.readValue(foodString, Food[].class);
        for (Food dish : food) {
            System.out.println(dish);
        }
    } catch (IOException e) {
        System.out.println("something went wrong");
        e.printStackTrace();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想用它反序列化我无法影响的json whiches内容(因此没有添加“适当”类型信息的选项)。我dishName遇到的问题是,显然json属性用于确定子类型,但是它没有反序列化到java字段中。有没有办法做到这一点?换句话说:main方法打印

null, type: Burger
null, type: Fries
null, type: Food
Run Code Online (Sandbox Code Playgroud)

在控制台上,但我希望它打印

burger, type: Burger
fries, type: Fries
cabbage, type: Food
Run Code Online (Sandbox Code Playgroud)

这特别令人讨厌,因为我以后没有办法发现最后一个对象是白菜。这使默认实现的好处无效。

编辑:

@Evil Raat的答案可以解决问题。为了完整起见:该示例dishName中的Food类需要使用@JsonPropertyAnnotation才能工作。因此,工作示例如下所示:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "dishName", defaultImpl = Food.class, visible = true)
@JsonSubTypes(value = {
    @Type(name = "fries", value = Fries.class),
    @Type(name = "burger", value = Burger.class)
})
public class Food {

  @JsonProperty
  private String dishName;

  @Override
  public String toString() {
    return dishName + ", type: " + this.getClass().getName();
  }
}

public class Fries extends Food { /*...*/ }

public class Burger extends Food { /*...*/ }

public class TryItOut {

  private static String foodString = "[ { \"dishName\":\"burger\" }, { \"dishName\":\"fries\" }, { \"dishName\":\"cabbage\" } ]";

  public static void main(String[] args) {
    ObjectMapper m = new ObjectMapper();
    try {
        Food[] food = m.readValue(foodString, Food[].class);
        for (Food dish : food) {
            System.out.println(dish);
        }
    } catch (IOException e) {
        System.out.println("something went wrong");
        e.printStackTrace();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

pmc*_*own 5

要保持用于反序列化的属性的值,只需在@JsonSubTypes批注上将visible属性设置为true即可:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "dishName", defaultImpl = Food.class, visible = true)