使用jackson-dataformat-yaml将对象序列化为yaml时无法删除标记



我用jackson (jackson-databinder &Jackson-dataformat-yaml)将多态性类序列化为json和yaml。我使用一个类属性作为类型解析器。我可以在json中删除类元数据信息,但在yaml中它仍然包含标签中的类元信息。我怎么能把它去掉呢?下面是我的示例代码:

@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) {
super();
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)
.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);
}

下面是json和yaml的输出:

{
"vehicles" : [ {
"name" : "Dodge",
"type" : "car"
}, {
"name" : "Scania",
"type" : "truck"
} ]
}
vehicles:
- !<car>
name: "Dodge"
type: "car"
- !<truck>
name: "Scania"
type: "truck"

json输出中没有类元信息。但在yaml中,仍然有包含类元信息的标签。有可能在yaml中删除json吗?由于

您可以禁用YAMLGenerator.Feature#USE_NATIVE_OBJECT_IDyaml特性,该特性在序列化中默认为指示类型启用。因此,在构建ObjectMapperYAML_MAPPER映射器时,您可以像下面这样禁用此功能,以获得预期的结果:

ObjectMapper YAML_MAPPER = YAMLMapper.builder()
.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) 
.disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID)
.build();

最新更新