jackSon中@JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType,@JsonProperty注解使用详解

概览

@JsonIgnore  用在字段上

@JsonIgnoreProperties  用在类上,指定忽略字段

@JsonIgnoreType  用在类上,忽略整个类

@JsonProperty 用于实体类的属性上, 功能是把属性名称转换为另一个名称(即,两个名称都指向同一个变量值)    --因代码不规范,或因与第三方对接,导致同一个表达含义使用了不同的字段.

上述注解都属于 jackson-databind 包下的注解,使用序列化时要使用该包下的类

// 序列化
new ObjectMapper().writeValueAsString(userDTO)

// 反序列化
new ObjectMapper().readValue(str.getBytes(),UserDTO.class)

@JsonIgnore

这个注解是用在字段上, 用来在实体类序列化和反序列化的时候忽略该字段字段。

public class User {
    @JsonIgnore
    private String username;
    private String password;
    private Integer age;
    }
    @RequestMapping("/a")
    public User test(@RequestBody User u) {
        User user = new User();
        user.setUsername("wkw");
        return user;
    }

访问这个接口返回的参数就不包含username这个字段了

{
  "password": null,
  "age": null
}

 然而我们访问这个接口带过去的参数username这个字段也不会反序列化

{
   "username" : "小明",
   "password" : "123",
   "age" : 15
}

反序列化username属性为空
在这里插入图片描述
由此可见当我们需要在序列化和反序列化的时候忽略某个字段的时候就用这个注解加在字段上面就行了。

@JsonIgnoreProperties

这个注解和@JsonIgnore注解功能是一样的,区别就是这个注解是用在类上面的,在需要的注解比较多的情况下,用来一次性定义忽略的字段

@JsonIgnoreProperties({"username","password"})
public class User {
    private String username;
    private String password;
    private Integer age;
    }

 还有一个用法就是配合allowGetters,allowSetters一起用用来控制字段忽视是在序列化还是反序列化,这样更加灵活,如下所示

//get为true的时候说明字段允许序列化,反序列的时候忽略该字段
@JsonIgnoreProperties(value = {"usname","password"},allowGetters = true)
public class User {
    private String username;
    private String password;
    private Integer age;
    }
//set为true说明字段允许反序列化,序列化的时候忽略该字段
@JsonIgnoreProperties(value = {"usname","password"},allowSetters = true)
public class User {
    private String username;
    private String password;
    private Integer age;

一般情况下,如果json字段转换为实体类即反序列化的时候,有字段无法对应实体类即会报错json解析异常,比如多一个属性,或属性名称写错无法对应。

这时只需要在实体类上面加注解即可解决,ignoreUnknown设置为true说明在反序列化的时候忽视未知的字段,即反序列的时候能对应的就对应上,不能对应的就不管了。

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private String username;
    private String password;
    private Integer age;
    }

@JsonIgnoreType

这个注解是用在类上面的表明这个类在序列化和反序列化的时候被忽略

比如我们下面有个User类,类上面加了注解 @JsonIgnoreType

@JsonIgnoreType
public class User {
    private String username;
    private String password;
    private Integer age;
    }

@JsonProperty

在序列化和反序列化过程中,对实体类属性做的映射,且必须要使用对应jackson包中的工具才可以得到@JsonProperty注解上指定的属性值.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDTO {

    /**
     * 用户id
     */
    @JsonProperty(value = "user_id")
    private String userId;

    /**
     * 用户名称
     */
    @JsonProperty(value = "user_name")
    private String userName;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值