You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让YAMLMapper读取含点号的YAML键以避免MismatchedInputException

解决YAMLMapper读取含点号键时的MismatchedInputException异常

问题原因

你遇到的MismatchedInputException异常,本质是因为原YAML中的formatting.template是单个完整的键名(包含点号),但你使用.at(/formatting/template)时,Jackson会按照层级节点去解析——也就是寻找formatting节点下的template子节点,而原YAML中根本不存在这样的层级结构,导致Jackson找不到可映射的内容,最终抛出"无输入可映射"的异常。

无需修改YAML的解决方案

方案1:先解析为Map再转换目标类

先将整个YAML文件解析成通用的Map,直接通过完整的带点键名取出对应的数据,再将其转换为目标类:

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);

    // 读取整个YAML为Map,保留原始键名(含点号)
    Map<String, Object> yamlMap = mapper.readValue(inputStream, new TypeReference<Map<String, Object>>() {});
    // 通过完整键名获取对应内容
    Object templateConfig = yamlMap.get("formatting.template");
    // 将内容转换为目标配置类
    return mapper.convertValue(templateConfig, FormattingConfigurationProperties.class);
}

方案2:利用@JsonRootName与解包根值特性

给目标配置类添加@JsonRootName注解,指定其对应的根键为formatting.template,再启用Jackson的UNWRAP_ROOT_VALUE特性,让Jackson自动识别带点号的根键并映射内容:

修改配置类

@Data
@JsonRootName("formatting.template") // 指定根键名称(含点号)
public class FormattingConfigurationProperties {

    private List<Field> fields;

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

}

修改读取方法

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);
    // 启用解包根值特性,让Jackson识别@JsonRootName指定的根键
    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

    return mapper.readValue(inputStream, FormattingConfigurationProperties.class);
}

内容的提问来源于stack exchange,提问作者Paul Marcelin Bejan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:00:46