使用Jackson序列化多态类到YAML时如何移除类型标签?
解决Jackson YAML序列化多态类型标签问题
要移除YAML输出里的!<car>这类类型标签,让它和JSON输出保持一致,只需要在构建YAMLMapper的时候,额外禁用YAMLGenerator.Feature.WRITE_TYPE_INFO_WITH_TAG这个特性就行。
修改后的核心代码
ObjectMapper YAML_MAPPER = YAMLMapper.builder() .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) // 关键:禁用类型标签的输出 .disable(YAMLGenerator.Feature.WRITE_TYPE_INFO_WITH_TAG) .build();
完整运行代码
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type") @JsonSubTypes({ @Type(value = Car.class, name = "car"), @Type(value = Truck.class, name = "truck") }) public interface Vehicle { String getName(); } @Value public static class Car implements Vehicle { String name; String type = "car"; @JsonCreator public Car(@JsonProperty("name") final String name) { this.name = requireNonNull(name); } } @Value public static class Truck implements Vehicle { String name; String type = "truck"; @JsonCreator public Truck(@JsonProperty("name") final String name) { this.name = requireNonNull(name); } } @Value public static class Vehicles { List<Vehicle> vehicles; @JsonCreator public Vehicles(@JsonProperty("vehicles") final List<Vehicle> vehicles) { this.vehicles = requireNonNull(vehicles); } } public static void main(String[] args) throws JsonProcessingException { ObjectMapper MAPPER = new ObjectMapper(); ObjectMapper YAML_MAPPER = YAMLMapper.builder() .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) .disable(YAMLGenerator.Feature.WRITE_TYPE_INFO_WITH_TAG) .build(); final Vehicles vehicles = new Vehicles(ImmutableList.of(new Car("Dodge"), new Truck("Scania"))); final String json = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(vehicles); System.out.println(json); final String yaml = YAML_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(vehicles); System.out.println(yaml); }
修改后的YAML输出
vehicles: - name: "Dodge" type: "car" - name: "Scania" type: "truck"
问题原因说明
Jackson的YAML生成器默认会把多态类型信息以YAML专属标签的形式输出,哪怕你已经通过@JsonTypeInfo指定了用type属性来传递类型信息。关掉WRITE_TYPE_INFO_WITH_TAG这个开关,YAML生成器就只会保留你定义的type字段,不再输出那些冗余的类型标签了。
内容的提问来源于stack exchange,提问作者zjffdu
相关产品推荐
相关产品推荐

