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

Java解析含引号与斜杠的JSON:提取400错误响应字段的最优方案

提取Spring HttpClientErrorException响应体错误字段的简洁方案

别用分隔符拆分这种脆弱的方式,直接用Spring默认集成的Jackson JSON库解析响应体,是更可靠简洁的方案,步骤如下:

  1. 捕获HttpClientErrorException.BadRequest异常,获取原始响应体字符串
  2. 清理非标准转义字符(比如<EOL>),如果是标准JSON转义可跳过此步
  3. 用Jackson将字符串解析为Map或自定义实体类,直接提取errorCode、message字段

示例代码

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.client.HttpClientErrorException;

// 自定义错误响应实体类(类型安全,推荐使用)
class ErrorResponse {
    private String errorCode;
    private String message;

    // 自动生成getter、setter
    public String getErrorCode() { return errorCode; }
    public void setErrorCode(String errorCode) { this.errorCode = errorCode; }
    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }
}

// 捕获异常并解析的逻辑
try {
    // 你的RestTemplate请求代码,比如:
    // restTemplate.getForObject("http://example.com/api", String.class);
} catch (HttpClientErrorException.BadRequest e) {
    String rawResponseBody = e.getResponseBodyAsString();
    // 清理非标准转义,比如<EOL>和多余的转义引号
    String cleanedBody = rawResponseBody.replace("<EOL>", "").replace("\\\"", "\"");
    
    ObjectMapper objectMapper = new ObjectMapper();
    // 方式1:解析到自定义实体类(类型安全)
    ErrorResponse errorResponse = objectMapper.readValue(cleanedBody, ErrorResponse.class);
    String errorCode = errorResponse.getErrorCode();
    String errorMsg = errorResponse.getMessage();

    // 方式2:解析到Map(无需实体类,适合快速原型)
    // Map<String, Object> errorMap = objectMapper.readValue(cleanedBody, new TypeReference<Map<String, Object>>() {});
    // String errorCode = (String) errorMap.get("errorCode");
    // String errorMsg = (String) errorMap.get("message");
}

优势

  • 比分隔符拆分更健壮,不受字段顺序、格式微调影响
  • 类型安全(用实体类的话),避免强制转换错误
  • 复用Spring自带的Jackson库,无需额外引入依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 18:53:27