【发布时间】:2022-12-10 12:08:47
【问题描述】:
我使用 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 删除?谢谢
【问题讨论】: