java后端返回给前端对象时去除值为空或NULL的属性参数

1.如果是string字符串 基本数据类型的设置

(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_NULL)

 

 2.测试接口时发现当返回的对象中属性值为 “” 或 [] 或 null 时,该属性依然会返回,这样数据看起来很不美观并且有时候也会导致前端组件出现一些小的bug。

如果children是空会出现如下图

解决--- 引入依赖

		<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
        </dependency>

使用 @JsonInclude 注解

只需要在实体类中的属性上面加上 @JsonInclude(JsonInclude.Include.NON_EMPTY) 

 注意:
1、 departmentCode 属性为 String 类型,String 的默认值为 null,所以注解里面要使用 JsonInclude.Include.NON_NULL。
2、children 属性为 List 类型,List 的默认值为 空 或 [] ,所以注解里面要使用 JsonInclude.Include.NON_EMPTY 。

可参考

children效果展示:

 

 结果展示

 

 

 

好的,下面是一个vue上传图片并且通过Java后端将图片转换成base64的代码示例: Vue前端部分: ``` <template> <div> <input type="file" @change="onFileChange"> </div> </template> <script> export default { methods: { onFileChange(event) { // 获取文件对象 const file = event.target.files[0] // 创建 FileReader 对象 const reader = new FileReader() // 读取文件 reader.readAsDataURL(file) // 文件读取完成后执行的回调函数 reader.onload = () => { // 获取 base64 编码的图片字符串 const base64Image = reader.result // 发送请求到后端 this.postImage(base64Image) } }, postImage(base64Image) { // 发送 Ajax 请求到后端 // 注意这里的 url 和请求方法要根据实际情况进行修改 axios.post('/api/uploadImage', { base64Image }).then(response => { console.log(response.data) }) } } } </script> ``` Java后端部分: ``` @RequestMapping(value = "/api/uploadImage", method = RequestMethod.POST) @ResponseBody public String uploadImage(@RequestBody Map<String, String> requestMap) { try { // 获取 base64 编码的图片字符串 String base64Image = requestMap.get("base64Image"); // 去掉字符串头部的 "data:image/png;base64," 部分 base64Image = base64Image.substring(base64Image.indexOf(",") + 1); // 解码 base64 编码的图片字符串 byte[] imageBytes = Base64.getDecoder().decode(base64Image); // 将图片字节流输出到文件 FileOutputStream imageOutFile = new FileOutputStream("image.jpg"); imageOutFile.write(imageBytes); imageOutFile.close(); // 将图片字节流转换成 base64 编码的字符串 String base64ImageString = Base64.getEncoder().encodeToString(imageBytes); return base64ImageString; } catch (IOException e) { e.printStackTrace(); return null; } } ``` 这段代码是一个简单的示例,具体实现还需要根据实际情况进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值