Jackson处理Json格式相关注解学习

1.指定字段不返回:@JsonIgnore

2.指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")

3.空字段不返回:@JsonInclude(Include.NON_NULL)

4.指定别名:@JsonProperty

测试:

SimpleController:

 @GetMapping("/testJson")
    Object testJson(){
        return new User(11,"13563986965",new Date(),"10010");
 }

Test1:

给用户的密码字段加上@JsonIgnore

  @JsonIgnore
  private String pwd;

测试返回结果:发现已经自动忽略掉了密码字段

{
    "age": 11,
    "phone": "13563986965",
    "birthday": "2020-05-25T03:00:16.558+00:00"
}

Test2:

给用户的生日字段加上:@JsonFormat

 @JsonFormat(pattern="yyyy-MM-dd",locale="zh",timezone="GMT+8")
 private Date birthday;

测试返回结果:发现用户的生日数据已经被格式化

{
    "age": 11,
    "phone": "13563986965",
    "birthday": "2020-05-25"
}

Test3:

给用户的用户名字段加上@JsonInclude(Include.NON_NULL),并且将用户名属性值置为Null

@GetMapping("/testJson")
Object testJson(){
   return new User(null,11,"13563986965",new Date(),"10010");
}
@JsonInclude(JsonInclude.Include.NON_NULL)
private String userName;

测试返回结果:发现用户的用户名字段不再显示

加注解@JsonInclude(Include.NON_NULL)前返回结果:

{
    "userName": "wjl",
    "age": 11,
    "phone": "13563986965",
    "birthday": "2020-05-25"
}

加注解@JsonInclude(Include.NON_NULL)前返回结果:

{
    "age": 11,
    "phone": "13563986965",
    "birthday": "2020-05-25"
}

Test4:

给用户的phone属性加上@JsonProperty注解:

@JsonProperty("电话号码")
private String phone;

 

测试结果:发现用户的phone的属性修改为“电话号码”:

{
    "userName": "wjl",
    "age": 11,
    "birthday": "2020-05-25",
    "电话号码": "13563986965"
}

 

你可能感兴趣的:(SpringBoot学习)