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

使用HttpClient发起GET请求时出现Unrecognized field异常

异常产生原因

Unrecognized field 是Jackson序列化/反序列化框架抛出的标准异常,触发场景为:

  • 你在Service层用ObjectMapper将HTTP接口返回的JSON字符串反序列化为ReadCaseByCaseNumberResponse类实例时,服务端实际返回的JSON结构中,存在当前响应实体类未定义的字段
  • Jackson默认配置下,遇到未知字段不会自动跳过,会直接抛出异常终止反序列化流程

常见的触发场景包括:

  • 服务端接口返回了实体类未声明的冗余字段,例如createTime、assignee、extInfo等扩展属性
  • 字段命名不匹配:例如服务端返回下划线命名的case_number,实体类定义为驼峰命名的caseNumber,或是字段拼写错误、大小写不一致,都会被Jackson判定为未知字段
  • 贴出的ReadCaseByCaseNumberResponse类代码不完整,缺失了部分和返回值对应的属性定义
修复方案

根据实际业务场景选择对应方案即可:

方案1:补全/修正响应实体类(最规范,优先推荐)

先打印EntityUtils.toString(response.getEntity())拿到接口实际返回的完整JSON原文,对照JSON结构:

  • 把所有返回的字段在ReadCaseByCaseNumberResponse类中补全,保证字段名、数据类型和返回值完全匹配
  • 如果存在命名风格不一致的情况,用@JsonProperty注解做显式映射,示例代码如下:
@Data
public class ReadCaseByCaseNumberResponse {
    private String id;
    // 映射服务端返回的下划线命名字段
    @JsonProperty("case_number")
    private Integer caseNumber;
    private String subject;
    private String description;
    private Integer version;
    private String status;
    private String priority;
    // 补全其他返回字段
    private String createTime;
    private String assignee;
}

方案2:配置ObjectMapper忽略未知字段(快速修复)

如果业务上不需要处理多余的返回字段,可以直接修改ObjectMapper的反序列化配置,关闭未知字段报错的开关,遇到未定义字段直接跳过:

ObjectMapper mapper = new ObjectMapper();
// 关闭未知字段抛异常的配置
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ReadCaseByCaseNumberResponse readCaseByCaseNumberResponse = mapper.readValue(
        EntityUtils.toString(response.getEntity()), 
        ReadCaseByCaseNumberResponse.class
);

如果项目中多处用到Jackson反序列化,可以把该配置的ObjectMapper定义为全局公用Bean,避免重复配置。

额外优化建议

当前代码存在资源泄漏风险,建议用try-with-resources语法自动关闭HTTP连接相关资源,避免连接耗尽:

// 把客户端、响应对象放到try括号里,执行完会自动释放资源
try (CloseableHttpClient client = HttpClients.createDefault();
     CloseableHttpResponse response = client.execute(httpGet)) {
    String responseStr = EntityUtils.toString(response.getEntity());
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(responseStr, ReadCaseByCaseNumberResponse.class);
}

另外注意配置项${servce.urlBasePath}存在拼写错误(正确应为service),避免配置注入失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 09:15:42