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

Java Spring试题创建接口JSON解析错误求助

解决Spring JSON反序列化枚举的错误

错误根源

你定义的Difficulty是枚举类型,Jackson默认无法将JSON里的普通字符串(比如你传入的"string")直接转换为枚举实例——要么是传入的字符串和枚举常量名称不匹配,要么是枚举类缺少适配的反序列化逻辑。

可行解决方案

1. 匹配枚举常量名称

如果你的Difficulty枚举是基础定义:

public enum Difficulty {
    EASY, MEDIUM, HARD
}

那么JSON请求里的difficulty值必须和枚举常量名完全一致(大小写敏感),比如:

{
  "difficulty": "EASY",
  // 其他字段...
}

2. 给枚举添加自定义序列化/反序列化逻辑

如果需要支持自定义字符串(比如中文描述),给枚举类加上Jackson注解,实现双向转换:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

public enum Difficulty {
    EASY("简单"),
    MEDIUM("中等"),
    HARD("困难");

    private final String label;

    Difficulty(String label) {
        this.label = label;
    }

    @JsonValue // 序列化时返回自定义标签
    public String getLabel() {
        return label;
    }

    @JsonCreator // 反序列化时根据输入字符串匹配枚举
    public static Difficulty fromInput(String input) {
        for (Difficulty diff : Difficulty.values()) {
            // 同时支持匹配枚举名和自定义标签,忽略大小写
            if (diff.name().equalsIgnoreCase(input) || diff.label.equalsIgnoreCase(input)) {
                return diff;
            }
        }
        throw new IllegalArgumentException("无效难度值: " + input);
    }
}

配置后,JSON里传"简单"或"EASY"都能正确映射到Difficulty.EASY。

3. 全局配置Jackson枚举反序列化策略

不想修改枚举类的话,可以通过Spring配置全局开启枚举的宽松反序列化:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 允许通过toString()匹配枚举,忽略大小写
        mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
        return mapper;
    }
}

这样JSON传入小写的"easy"也能正确解析为Difficulty.EASY。

额外检查点

  • 确认QuestionInput类中difficulty字段的类型是Difficulty而非String
  • 检查DTO转换器中是否正确处理了Difficulty类型的转换逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:48:18