Spring boot项目Controller层返回实体过滤为null的属性

本文介绍了如何通过在Java对象类上添加@JsonInclude(JsonInclude.Include.NON_NULL)注解,来过滤接口响应中值为null的字段。示例展示了在ResponseObj类和Controller层方法中应用该注解,从而优化返回结果,减少不必要的空值信息。

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

在写项目时,有时候会希望在接口层返回的字段中过滤掉为null值的字段,可以在返回的对象类上加上注解@JsonInclude(JsonInclude.Include.NON_NULL)

举例如下:

1、自定义返回方法体:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

@JsonInclude(Include.NON_EMPTY)
public class ResponseObj<T> {
    private T result;
    private Integer code;
    private String msg;

    public ResponseEnvelope(T result) {
        this.result = result;
        this.code = 200;
    }

    public T getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

Controller层接口方法:

@GetMapping("/param/stu")
public ResponseEntity<ResponseObj<Stu>> StuTest(@RequestParam Long id){
    LOG.info("进入控制层");
    Stu stu = stuService.selectById(id);
    ResponseObj<Stu> response = new ResponseObj<>(stu);
    return new ResponseEntity<>(response, HttpStatus.OK);
}

返回结果:

如果没有加上注解@JsonInclude(JsonInclude.Include.NON_NULL)的话,返回结果:

 

 

 

Spring Boot项目中创建Controller的步骤如下: 1. 首先,创建一个Spring Boot项目。可以使用IDE工具(如IntelliJ IDEA、Eclipse等)或者使用Spring Initializr(https://start.spring.io/)来创建项目。在创建项目时,选择适当的依赖项,包括Spring Web依赖。 2. 在项目的源代码目录下,创建一个新的Java类,作为Controller。这个类需要使用@Controller或@RestController注解进行标记,以指示它是一个控制器类。 3. 在Controller类中,创建一个处理HTTP请求的方法。这个方法需要使用@RequestMapping或@GetMapping等注解来指定请求的URL路径和HTTP方法。方法的返回值可以是一个字符串,表示要返回的响应内容,或者是一个对象,表示要返回的JSON数据。 4. 在方法中,可以使用@RequestParam注解来获取请求参数,使用@PathVariable注解来获取URL路径中的参数。 5. 在方法中,可以使用@Autowired注解来注入其他的Spring组件,如Service或Repository。 6. 最后,运行Spring Boot应用程序,并通过浏览器或其他HTTP客户端发送请求来测试Controller的功能。 需要注意的是,Spring Boot遵循"约定大于配置"的思想,因此在创建Controller时,需要遵循一定的规范,如类的路径不能随意放置。但是,Spring Boot框架不需要我们手动设置配置文件,它提供了默认的配置和自动配置功能,使得开发更加快捷和方便。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *2* *3* [创建并运行一个 Spring Boot 项目](https://blog.youkuaiyun.com/lfm1010123/article/details/127094991)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值