前后端分离使用Jackson或者fastjson解决后端忽略实体类中的某个属性不返回给前端的方法【亲测有用】

导读:本篇文章讲解 前后端分离使用Jackson或者fastjson解决后端忽略实体类中的某个属性不返回给前端的方法【亲测有用】,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、前言

接收到的需求:我们前端只需要id、name、gender,phone不需要给前端。
一开始想法直接重新写一个VO,属性里去掉phone,这样一下多了个文件,显然不是我们想要的!接下来教你两种方式实现一下哦!!

二、导入maven

<!-- 第一种:jackson-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
</dependency>

<!-- 第二种:fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.69</version>
</dependency>

三、不使用之前效果展示

在这里插入图片描述

四、期望

在这里插入图片描述

五、Jackson实现

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.io.Serializable;

@Data
public class Test implements Serializable {
    private static final long serialVersionUID = 337361630075002456L;

    private String id;

    private String name;
    
    private String gender;

    @JsonIgnore
    private String phone;
    
}

六、Fastjson实现

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;

import java.io.Serializable;

@Data
public class Test implements Serializable {
    private static final long serialVersionUID = 337361630075002456L;

    private String id;

    private String name;

    private String gender;
    
    @JSONField(serialize = false)
    private String phone;

}

两个不要一起使用,不然不起作用**


其中fastjson这样还不起作用,我们需要在启动项里配置一下

感谢原文作者—>地址

@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    fastConverter.setFastJsonConfig(fastJsonConfig);
    HttpMessageConverter<?> converter = fastConverter;
    return new HttpMessageConverters(converter);
}

七、总结

这样就可以解决忽略某些属性不返回给前端展示了,对你有用点个赞呗!!!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/85245.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!