【问题标题】:Unable to remove tag when serializing object to yaml using jackson-dataformat-yaml使用 jackson-dataformat-yaml 将对象序列化为 yaml 时无法删除标签
【发布时间】: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 删除?谢谢

【问题讨论】:

    标签: java json jackson yaml


    【解决方案1】:

    您可以禁用默认情况下为序列化中的指示类型启用的 YAMLGenerator.Feature#USE_NATIVE_OBJECT_ID yaml 功能。因此,在构建 ObjectMapper YAML_MAPPER 映射器时,您可以禁用此功能,如下所示,以获得预期结果:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-08
      • 2019-03-17
      • 1970-01-01
      • 2017-10-24
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多