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

Java Spring中如何将JSON数组嵌套的Date值转为纯字符串响应数组

Java Spring接口响应结构调整解决方案
  • 核心调整逻辑:将jdbcTemplate返回的行级Map结构,转换为格式化后的字符串列表,直接作为响应的data字段值,无需额外对象包裹。

代码调整步骤

方式1:在业务层处理返回结果(无需修改Repository层代码)

原响应构造代码调整如下:

import java.util.stream.Collectors;

// 调用Repository获取原始存储过程返回结果
List<Map<String, Object>> holidayMapList = simulationRepository.getHoliday(Tahun);
// 遍历处理日期格式,生成目标字符串列表
List<String> formatHolidayList = holidayMapList.stream()
        .map(rowMap -> {
            String originDate = (String) rowMap.get("Date");
            return originDate.replace("/", "-");
        })
        .collect(Collectors.toList());
// 直接将字符串列表设置到响应对象
responseArray.setData(formatHolidayList);
responseArray.setMessage("OK");

注:如果使用JDK 16及以上版本,可直接用.toList()替代.collect(Collectors.toList())

方式2:在Repository层封装处理逻辑(上层调用更简洁)

首先调整Repository层的getHoliday方法返回值与处理逻辑:

import java.util.stream.Collectors;

final String SELECT_QUERY_getDate = "exec spGetDate ?";
public List<String> getHoliday(String Year) {
    List<Map<String, Object>> originResult = jdbcTemplateThree.queryForList(SELECT_QUERY_getDate, Year);
    // 直接在Repository层完成格式转换
    return originResult.stream()
            .map(rowMap -> ((String) rowMap.get("Date")).replace("/", "-"))
            .collect(Collectors.toList());
}

调整后业务层响应构造代码简化为:

List<String> holidayList = simulationRepository.getHoliday(Tahun);
responseArray.setData(holidayList);
responseArray.setMessage("OK");

补充说明

需要确认全局响应对象responseArray的setData方法支持传入List<String>类型,若原方法参数为List<ResponGetHoliday>,可直接将响应类的data字段类型修改为List<String>即可,原ResponGetHoliday类可不再使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:57:03