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

Spring Boot中如何用RestTemplate提取外部REST API的JSON响应数据?

提取JSON单个数据的几种适配方案(针对你的Spring Boot场景)

一、直接用已映射的POJO提取(最优推荐)

既然你已经通过RestTemplate把外部API响应映射到了对应POJO,完全没必要再用JSONObject绕弯,直接调用POJO的getter就能拿到单个数据,还能避免解析异常。

举个实际例子:
假设外部API的响应POJO是ExternalApiResponse,包含userList(用户数组)和totalCount(总条数)字段,要提取单个用户信息或统计值:

// 服务类中已获取到映射好的POJO实例
ExternalApiResponse apiResponse = restTemplate.getForObject(externalApiUrl, ExternalApiResponse.class);

// 提取第一个用户的姓名
String firstUserName = apiResponse.getUserList().get(0).getUserName();
// 提取总用户数
int totalUserNum = apiResponse.getTotalCount();

之后直接将数据转换为你的自定义POJO,比如CustomUser:

List<CustomUser> customUserList = apiResponse.getUserList().stream()
    .map(user -> new CustomUser(user.getUserName(), user.getEmail(), user.getCreateTime()))
    .collect(Collectors.toList());

二、手动解析JSON(需绕开已有POJO时)

如果确实需要处理原始JSON字符串,推荐用Spring自带的Jackson ObjectMapper,比第三方JSONObject更适配Spring生态,能避免依赖冲突导致的异常:

  1. 先获取原始JSON响应字符串:
String rawJson = restTemplate.getForObject(externalApiUrl, String.class);
  1. 用ObjectMapper解析单个字段:
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(rawJson);

// 提取根节点下的单个字段
int totalCount = rootNode.get("totalCount").asInt();
// 提取嵌套数组里的字段:比如第一个用户的邮箱
String firstUserEmail = rootNode.get("userList").get(0).get("email").asText();

关于JSONObject异常的说明

你遇到的异常大概率是因为JSON结构嵌套复杂,或者引入的JSONObject依赖(比如org.json)和Spring自带的Jackson版本冲突,导致解析逻辑报错,用Jackson的ObjectMapper能规避这类问题。

三、前端AJAX渲染到HTML表格

后端把处理好的自定义POJO集合封装成JSON接口返回后,前端用AJAX请求并渲染表格:

// 假设后端接口地址为/api/custom-users
$.ajax({
    url: "/api/custom-users",
    type: "GET",
    success: function(data) {
        const tableBody = document.querySelector("#userTable tbody");
        tableBody.innerHTML = "";
        data.forEach(user => {
            const row = `<tr>
                        <td>${user.userName}</td>
                        <td>${user.email}</td>
                        <td>${user.createTime}</td>
                      </tr>`;
            tableBody.insertAdjacentHTML("beforeend", row);
        });
    },
    error: () => alert("数据加载失败")
});

对应的HTML表格结构:

<table id="userTable">
    <thead>
        <tr>
            <th>用户名</th>
            <th>邮箱</th>
            <th>创建时间</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:50:40