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

使用ObjectMapper解析JSON时出现complaintResponse无法识别错误如何解决

解决ObjectMapper反序列化接口响应提取sr_number报错问题

报错核心原因

你仅定义了最内层的ComplaintResponse实体类,而接口返回的JSON是多层嵌套结构:最外层有status/errorCode/data字段,data内部才是complaintResponse对象。直接将完整响应JSON反序列化为ComplaintResponse类时,Jackson无法匹配外层字段,也找不到complaintResponse对应的接收属性,因此抛出无法识别的错误。


解决方案

方案1:定义完整嵌套实体类(推荐,可复用性高)

补充外层匹配结构的实体类即可,原有ComplaintResponse无需修改:

import lombok.Data;

// 1. 最外层接口响应实体
@Data
public class ApiResponse {
    private String status;
    private String errorCode;
    private String errorDescription;
    private ApiData data;
}

// 2. 中间层data对应的实体
@Data
public class ApiData {
    private ComplaintResponse complaintResponse;
}

// 3. 你原有定义的ComplaintResponse保持不变
@Data
public class ComplaintResponse {
    private String issueId;
    private String sr_number;
}

反序列化取值代码:

ObjectMapper objectMapper = new ObjectMapper();
ApiResponse apiResponse = objectMapper.readValue(完整响应json字符串, ApiResponse.class);
// 直接获取sr_number
String srNumber = apiResponse.getData().getComplaintResponse().getSr_number();

方案2:直接解析JSON节点取值(适合临时单次取值场景)

不需要额外定义实体类,逐层读取JSON节点即可:

ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(完整响应json字符串);
// 逐层定位到sr_number字段取值
String srNumber = rootNode.get("data")
        .get("complaintResponse")
        .get("sr_number")
        .asText();

// 如果需要转成ComplaintResponse对象,也可以单独转换对应节点
ComplaintResponse resp = objectMapper.convertValue(
        rootNode.get("data").get("complaintResponse"),
        ComplaintResponse.class
);

方案3:补充忽略未知字段配置(避免多余字段报错)

如果已经定义了嵌套实体还是报错,可添加配置关闭Jackson的未知字段校验:

  • 全局配置ObjectMapper:
import com.fasterxml.jackson.databind.DeserializationFeature;

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  • 或者给实体类加注解:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiResponse {
    // 类属性不变
}

如果是字段命名策略不匹配导致complaintResponse识别失败,可给对应属性添加@JsonProperty手动指定匹配字段名:

@Data
public class ApiData {
    @JsonProperty("complaintResponse")
    private ComplaintResponse complaintResponse;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:54:04