【转载】jackson 的几个注解

注解@JsonIgnoreProperties, by 弄玉x

一、jackson 的 mavern 依赖

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

二、使用的背景
springboot 项目中定义了很多类,我们在 rest 返回中直接返回或者在返回对象中使用这些类,spring 已经使用 jackson 自动帮我们完成这些的 to json。但是有时候自动转的 json 内容太多,或者格式不符合我们的期望,因此需要调整类的 to json 过程,或者说希望自定义类的 json 过程。
三、@JsonProperty
1、概念:

  • 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把 trueName 属性序列化为 name,@JsonProperty(“name”)。
  • 对属性名称重命名,比如在很多场景下 Java 对象的属性是按照规范的驼峰书写,但在数据库设计时使用的是下划线连接方式,此处在进行映射的时候就可以使用该注解。

2、用法
例如:使用该注解将以下表结构转化为 Javabean:

public class CustomerInfo{
    
    private int id;

    //使用 @JsonProperty注解将表结构中的字段映射到实体类中
    @JsonProperty("customer_name")
    private String customerName;
    
    @JsonProperty("customer_id")
    private String customerId;
    
    @JsonProperty("product_id")
    private String productId;
    
    @JsonProperty("source_address")
    private String sourceAddress;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public String getSourceAddress() {
        return sourceAddress;
    }

    public void setSourceAddress(String sourceAddress) {
        this.sourceAddress = sourceAddress;
    }
}

四、@JsonIgnore
1、概念

  • 用于属性或者方法上(最好是属性上),用来完全忽略被注解的字段和方法对应的属性,即便这个字段或方法可以被自动检测到或者还有其他的注解,一般标记在属性或者方法上,返回的 json 数据即不包含该属性。

2、用法
使用情景:需要把一个 List 转换成 json 格式的数据传递给前台。但实体类中基本属性字段的值都存储在快照属性字段中。此时我可以在业务层中做处理,把快照属性字段的值赋给实体类中对应的基本属性字段。最后,我希望返回的 json 数据中不包含这两个快照字段,那么在实体类中快照属性上加注解 @JsonIgnore,那么最后返回的 json 数据,将不会包含 customerId 和 productId 两个属性值。

public class CustomerInfo {
    
    private int id;
    
    //使用 @JsonIgnore注解在生成json数据时,忽略该字段
    
    private String customerName;
    
    @JsonIgnore
    private String customerId;
    
    @JsonIgnore
    private String productId;
    
    private String sourceAddress;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public String getSourceAddress() {
        return sourceAddress;
    }

    public void setSourceAddress(String sourceAddress) {
        this.sourceAddress = sourceAddress;
    }
}

五、@JsonIgnoreProperties
1、概念:
是类注解,作用是 json 序列化时将 java bean 中的一些属性忽略掉,序列化和反序列化都受影响。
2、用法:
@JsonIgnoreProperties(ignoreUnknown = true),将这个注解写在类上之后,就会忽略类中不存在的字段。

  • 使用
@Data
@JsonIgnoreProperties(value = {"fullName", "comment"})
public class User {
    private String id;
    private String name;
    private String fullName;
    private String comment;
    private String mail;

    @JsonIgnore
    private String address;

    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date regDate;

    private Date reg2Date;
}



说明:User 类的 fullName 和 comment 字段会被 @JsonIgnoreProperties 注解忽略。address 字段会被 @JsonIgnore 注解忽略。regDate 会按照 @JsonFormat(timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”) 进行格式转。

  • 我们的 controller 示例代码:
    @ApiOperation(value = "按用户id删除", notes="private")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", defaultValue = "2", value = "userID", required = true, dataType = "string", paramType = "path"),
    })
    @DeleteMapping(value = "/users/{userId}", produces = "application/json;charset=UTF-8")
    public User delUser(@PathVariable String userId) {
        User user = (User)userSvc.deleteById(userId);
        log.info("rest del user={} by id={}", user, userId);
        return user;
    }


  • 可以看到返回的对象是 User,然后 comment、fullName、address 属性被忽略了,regDate 的格式进行转换。![]( https://img-blog.csdnimg.cn/20200928143036147.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQ2MDY5ODYx,size_16,color_FFFFFF,t_70#pic_center)
    六、@JsonFormat
    1、概念:
    用于属性或者方法上(最好是属性上),可以方便的把 Date 类型直接转化为我们想要的模式。
    2、用法:
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date updateTime;

七、@JsonSerialize
用于属性或者 getter 方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个 double 时在其后面限制两位小数点。
八、@JsonDeserialize
用于属性或者 setter 方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的 @JsonSerialize。
九、@JsonInclude
属性值为 null 的不参与序列化。例子:@JsonInclude(Include.NON_NULL)。

posted @ 2023-02-18 20:41  洗衣机o  阅读(70)  评论(0)    收藏  举报