如何在 java spring 中使用 jackson 将 collection 转换为 csv?

How to convert collection to csv with jackson in java spring?

我在使用 jackson 将 java.util.Collection 转换为 csv 文件时遇到问题。

在下面的代码中,您可以看到将 collection 转换为 csv-string 的方法。

但我需要一种方法来将 collection 转换为 com.fasterxml.jackson。 枚举 "DownloadType" 获取 csv 文件的列和标题行。

你有解决办法吗?

@RequestMapping(value = "/csv",
            produces = {"text/csv"},
            consumes = {"application/json"},
            method = RequestMethod.POST)
public ResponseEntity<Object> exportCsv()
{
    ResponseEntity<Object> response = null;
    try
    {
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, "text/csv; charset=UTF-8");
            headers.add(HttpHeaders.CACHE_CONTROL, "no-store, must-revalidate");
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"export.csv\"");
            headers.add(HttpHeaders.EXPIRES, "0");

            byte[] csvBytes = null;
            byte[] headerBytes = null;
            byte[] lineBytes = null;
            CsvMapper mapper = new 
            Collection<User> users = getUsers()
            headerBytes = DownloadType.USER.getHeaderLine().getBytes("UTF-8");
            lineBytes = mapper.writer(DownloadType.USER.getCsvSchema()).writeValueAsBytes(users);
            if (headerBytes != null && lineBytes != null)
            {
                csvBytes = new byte[headerBytes.length + lineBytes.length];
                System.arraycopy(headerBytes, 0, csvBytes, 0, headerBytes.length);
                System.arraycopy(lineBytes, 0, csvBytes, headerBytes.length, lineBytes.length);
            }
            response = new ResponseEntity<>(csvBytes, headers, HttpStatus.OK);


    }
    catch (Exception e)
    {
        LOG.error(e.getMessage(), e);
    }
    return response;
}

也许试试这样的方法。通过将数据直接写入 servlet 响应,字符串将按原样直接返回给客户端,无需格式化或 post-processing.

@RequestMapping(value = "/csv",
            produces = {"text/csv"},
            consumes = {"application/json"},
            method = RequestMethod.POST)
public void exportCsv(HttpServletResponse response)
{
    ...
    String headerString = DownloadType.USER.getHeaderLine()
    String data = mapper.writer(DownloadType.USER.getCsvSchema()).writeValueAsString(users);
response.setContentType("text/plain; charset=utf-8");
    response.getWriter().print(headerString);
    response.getWriter().print(data);

改编自: How to Return CSV Data in Browser From Spring Controller