springboot 返回数据为null

本文介绍如何在SpringBoot项目中配置Jackson,以实现对JSON中null字段的处理。提供了两种方法:一是通过配置文件设置null字段不显示;二是将null字段转换为空字符串,并附带详细代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot默认使用jackson解析返回json数据。

处理方法1、返回json中的null字段-不显示 

配置文件添加 spring.jackson.default-property-inclusion=non_null 配置

处理方法2、返回json中的null字段-转为空字符串

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
 
import java.io.IOException;
 
/**
 * 处理 jackson 返回的null值
 * 返回json中的null值转为空字符串
 */
@Configuration
public class JacksonConfig {
 
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

 

### 使用 Spring Boot 实现数据导出至 Excel 的方法 #### 准备工作 为了实现这一目标,首先需要准备必要的环境配置。确保项目已经引入了所需的依赖项,特别是 Apache POI 或 EasyExcel 库,这些库用于操作 Excel 文件[^1]。 对于基于 Maven 构建工具的项目,在 `pom.xml` 中添加如下依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> <!-- 如果选择使用EasyExcel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.0.5</version> </dependency> ``` #### 创建控制器类 接下来创建一个 RESTful API 控制器来处理 HTTP 请求并返回 Excel 文件流给客户端。这里假设有一个简单的实体模型 `User` 表示要导出的数据记录[^3]。 ```java @RestController @RequestMapping("/api/export") public class ExportController { @Autowired private UserService userService; @GetMapping(value = "/users", produces = "application/vnd.ms-excel") public void exportUsers(HttpServletResponse response) throws IOException { List<User> users = userService.getAllUsers(); // 设置响应头信息 response.setContentType("application/octet-stream"); String headerKey = "Content-Disposition"; String headerValue = "attachment; filename=users.xlsx"; response.setHeader(headerKey, headerValue); // 将数据写入Excel文件 try (OutputStream out = response.getOutputStream()) { writeDataToExcel(users, out); out.flush(); } } } ``` #### 编写业务逻辑层代码 在服务层编写具体的业务逻辑,负责获取待导出的数据集,并调用辅助函数完成实际的 Excel 写入操作。 ```java @Service public class UserServiceImpl implements UserService { @Override public List<User> getAllUsers() { // 这里可以是从数据库查询得到的结果集合 return userRepository.findAll(); } } ``` #### 定义辅助方法以生成 Excel 文档 最后一步是在工具类中定义静态方法 `writeDataToExcel()` 来构建 Excel 工作簿对象,并填充相应的单元格内容。 ```java private static void writeDataToExcel(List<User> userList, OutputStream outputStream) throws IOException { Workbook workbook = new XSSFWorkbook(); // 可选 HSSFWorkbook 对于 .xls 格式的文件 Sheet sheet = workbook.createSheet("用户列表"); int rowNum = 0; Row row = sheet.createRow(rowNum++); // 添加表头 CellStyle headCellStyle = createHeadCellStyle(workbook); setCellValueWithStyle(row.createCell(0), "ID", headCellStyle); setCellValueWithStyle(row.createCell(1), "姓名", headCellStyle); setCellValueWithStyle(row.createCell(2), "邮箱地址", headCellStyle); // 填充数据行 for (User user : userList) { row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(user.getId()); row.createCell(1).setCellValue(user.getName()); row.createCell(2).setCellValue(user.getEmailAddress()); } workbook.write(outputStream); workbook.close(); } // 辅助方法设置单元格样式和值 private static void setCellValueWithStyle(Cell cell, Object value, CellStyle style){ if(style != null){ cell.setCellStyle(style); } if(value instanceof Integer || value instanceof Long){ cell.setCellValue(((Number)value).doubleValue()); }else{ cell.setCellValue(String.valueOf(value)); } } // 创建表头样式的辅助方法 private static CellStyle createHeadCellStyle(Workbook wb){ CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setFontHeightInPoints((short)12); font.setBold(true); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setBorderBottom(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); style.setBorderTop(BorderStyle.THIN); style.setFont(font); return style; } ``` 上述流程展示了如何利用 Spring Boot 结合 Apache POI 或者 Alibaba 开源组件 EasyExcel 来快速有效地实现出口 Excel 功能。此方案不仅能满足基本的数据报表需求,还具备良好的可扩展性和维护性[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值