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

如何使用Jackson实现Java枚举与YAML的序列化/反序列化?

解决Jackson反序列化YAML枚举大小写不匹配的问题

问题原因

YAML文件中枚举值为小写(counter),但Java枚举常量为大写(COUNTER),Jackson默认严格匹配枚举名称,导致反序列化失败。

解决方案

方案1:给枚举添加Jackson注解指定别名

直接在枚举常量上标注@JsonProperty,指定对应的YAML字符串值:

public class Metric {
    public enum Type {
        @JsonProperty("counter")
        COUNTER,
        @JsonProperty("gauge")
        GAUGE
    }

    // 其他属性及getter/setter
}

或者用更灵活的方式,通过@JsonValue和@JsonCreator自定义序列化/反序列化逻辑,还支持忽略大小写:

public class Metric {
    public enum Type {
        COUNTER("counter"),
        GAUGE("gauge");

        private final String yamlValue;

        Type(String yamlValue) {
            this.yamlValue = yamlValue;
        }

        @JsonValue
        public String toYamlValue() {
            return yamlValue;
        }

        @JsonCreator
        public static Type fromYamlValue(String value) {
            for (Type type : Type.values()) {
                if (type.yamlValue.equalsIgnoreCase(value)) {
                    return type;
                }
            }
            throw new IllegalArgumentException("无效的Metric类型:" + value);
        }
    }

    // 其他属性及getter/setter
}

方案2:配置ObjectMapper忽略枚举大小写

修改Parser中的ObjectMapper初始化,启用枚举大小写不敏感的反序列化特性,无需修改枚举类:

public class Parser {
    private ObjectMapper mapper = new ObjectMapper(new YAMLFactory())
            .enable(DeserializationFeature.READ_ENUMS_CASE_INSENSITIVE);

    public void parse() throws StreamReadException, DatabindException, IOException {
        Metric m = mapper.readValue(new File("data.yaml"), Metric.class);
    }
}

验证

修改后重新运行解析代码,YAML中的counter即可正确映射到Metric.Type.COUNTER枚举常量。

内容的提问来源于stack exchange,提问作者Joseph Gagnon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:13:23