使用 Jackson 反序列化带有根名称前缀的 YAML

Deserializing YAML with root name prefix using Jackson

我想使用 Jackson 和 jackson-dataformat-yaml 将 YAML 文件反序列化为 Java 对象。

YAML 是

company:
  product:
    settings:
      property: value

目标class是

@Getter @Setter
public class TargetObject {
  private Map<String, String> settings;
}

反序列化代码为

  TargetObject config =
  new ObjectMapper(new YAMLFactory())
      .readerFor(TargetObject.class)
      .withRootName("company.product")
      .readValue(yamlResource.getInputStream());

执行此代码时出现以下异常:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Root name ('company') does not match expected ('company.product') for type `a.b.c.TargetObject`

没有第二个嵌套“产品”一切正常。有没有可能在不接触 YAML 的情况下解决这个问题?我读过有关将点转义为 YAML 键的信息,例如 "[company.product]",但遗憾的是,这在我的用例中不是一个选项。

问候,六甲

您非常接近解决方案,问题在于您在代码中使用了错误的 ObjectReader#withRootName 方法:

TargetObject config =
  new ObjectMapper(new YAMLFactory())
      .readerFor(TargetObject.class)
      .withRootName("company.product") //<-- here the error
      .readValue(yamlResource.getInputStream());

相反,您必须使用 ObjectReader#at 方法 select 您感兴趣的 yaml 部分以及适当的 "/company/product" 路径以获得预期结果:

TargetObject config = 
  new ObjectMapper(new YAMLFactory())
      .readerFor(TargetObject.class)
      .at("/company/product") //<--here the new method
      .readValue(yamlResource.getInputStream());