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

Java REST API如何将JSON响应转换为制表符分隔的大写TXT文件

问题根源

你当前代码直接返回List<Abc>实体类集合,Spring MVC会默认使用Jackson消息转换器将其序列化为JSON格式,因此即便设置了txt后缀的文件名,文件内容仍然是JSON结构。

修改方案

你需要手动构造制表符分隔的文本内容,避免Spring自动做JSON序列化,修改步骤如下:

  1. 修改接口返回值类型为ResponseEntity<String>
  2. 遍历查询到的Abc集合,逐行拼接字段,字段间用制表符\t分隔,所有内容统一转为大写
  3. 显式设置响应Content-Type为text/plain
修改后完整代码
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
// 其余原有导入保持不变

@RequestMapping(value = "/abc/export", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> getProviderExport(@RequestParam String id, HttpServletResponse response){
    List<Abc> abcdetails = jdbcTemplate.query(sqlQuery, new BeanPropertyRowMapper<Abc>(Abc.class));
    // 构造文本内容
    StringBuilder contentBuilder = new StringBuilder();
    // 可选:先写入表头,按需开启
    // contentBuilder.append("ABC_ID\tRECIP_ID\tRECIP_FIRST_NAME\tRECIP_MIDDLE_NAME\n");
    for (Abc abc : abcdetails) {
        // 逐行拼接字段,制表符分隔,所有内容转大写
        contentBuilder.append(String.valueOf(abc.getABC_ID()).toUpperCase()).append("\t")
                .append(abc.getRECIP_ID() != null ? abc.getRECIP_ID().toUpperCase() : "").append("\t")
                .append(abc.getRECIP_FIRST_NAME() != null ? abc.getRECIP_FIRST_NAME().toUpperCase() : "").append("\t")
                .append(abc.getRECIP_MIDDLE_NAME() != null ? abc.getRECIP_MIDDLE_NAME().toUpperCase() : "").append("\n");
    }
    HttpHeaders responseHeaders = new HttpHeaders();
    String filename1 = "output.txt";
    // 正确设置响应类型
    responseHeaders.setContentType(MediaType.TEXT_PLAIN);
    response.setCharacterEncoding("UTF-8");
    // 文件名编码处理,避免后续如果修改为中文文件名出现乱码
    String encodeFileName = URLEncoder.encode(filename1, StandardCharsets.UTF_8);
    responseHeaders.add("Content-Disposition","attachment; filename="+encodeFileName);
    return new ResponseEntity<>(contentBuilder.toString(), responseHeaders, HttpStatus.OK);
}

注意请确保Abc类的所有字段都已经生成对应的getter方法,代码中已做null值判断避免空指针异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:27:01