jackson YAMLMapper输入不匹配异常YAML键带有句点

hivapdat  于 2023-02-12  发布在  其他
关注(0)|答案(1)|浏览(134)

发生错误:Jackson。输入不匹配异常:由于输入结束,没有要Map的内容
Yaml文件:

formatting.template:
  fields:
    - name: birthdate
      type: java.lang.String
      subType: java.util.Date
      lenght: 10

配置属性:

@Data
public class FormattingConfigurationProperties {

    private List<Field> fields;

    @Data
    public static class Field {
        private String name;
        private String type;
        private String subType;
        private String lenght;
    }

}

方法读取yaml

private static FormattingConfigurationProperties buildFormattingConfigurationProperties() throws IOException {

    InputStream inputStream = new FileInputStream(new File("./src/test/resources/" + "application_formatting.yaml"));
    
    YAMLMapper mapper = new YAMLMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

    return mapper.readerFor(FormattingConfigurationProperties.class)
                 .at(/formatting/template)
                 .readValue(inputStream);

}

我实际上通过更改Yaml文件解决了这个问题,将格式化.template拆分为单独的行:

formatting:
  template:
    fields:
      - name: birthdate
        type: java.lang.String
        subType: java.util.Date
        lenght: 10

这意味着无法读取带点(句点(.))的键。有人知道如何避免MismatchedInputException,当前缀在同一行上由点分隔时?

n3h0vuf2

n3h0vuf21#

您正在使用JSON指针/formatting/template。这是用于嵌套Map的,如第二个YAML文件所示。如果您有一个压缩键formatting.template,则需要JSON指针/formatting.template
YAML完全能够读取带有点的键,它只是没有做你认为它做的事情。点在YAML中不是特殊字符,只是内容的一部分。
您可能使用过Spring,它通过将YAML文件重写为Properties文件来加载YAML文件,其中. * 是 * 分隔符。由于现有的点没有转义,因此对于Spring使用的YAML文件,点与嵌套键相同。然而,当您直接使用YAML加载程序(如Jackson)时,情况并非如此。

相关问题