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

Java17如何提取JSON数组中同名value参数并拆分为独立参数

解决方案

你需要先提取顶层的data数组,再分别获取数组内两个下标对应对象的value字段值,适配你现有代码的实现如下:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.web.client.RestTemplate;
import java.text.ParseException;

private RestTemplate restTemplate = new RestTemplate();
private static final String FANG_URL = "https://api.alternative.me/fng/?limit=2";

public FangDto getFangFromLastTwoDays() throws ParseException {
    String response = restTemplate.getForObject(FANG_URL, String.class);
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = (JSONObject) parser.parse(response);
    // 提取顶层data数组
    JSONArray dataArray = (JSONArray) jsonObj.get("data");
    // 分别获取两个对象的value值,下标0为最新数据,下标1为前一天数据
    JSONObject latestData = (JSONObject) dataArray.get(0);
    String latestValue = (String) latestData.get("value");
    JSONObject previousData = (JSONObject) dataArray.get(1);
    String previousValue = (String) previousData.get("value");
    
    // 组装到FangDto中,可根据你的Dto实际字段调整赋值逻辑
    FangDto fangDto = new FangDto();
    fangDto.setLatestValue(latestValue);
    fangDto.setPreviousValue(previousValue);
    return fangDto;
}

注意事项

  • 可根据业务需要把value的字符串类型转成Integer等数值类型使用
  • 上线前建议增加数组长度校验、空值判断逻辑,避免API返回数据结构变化时抛出空指针或下标越界异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:48:01