@JsonProperty,@JsonIgnore,@NotFound(action=NotFoundAction.IGNORE)等校验注解的使用

@JsonProperty的使用:
@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty(“name”)。

import com.fasterxml.jackson.annotation.JsonProperty; 
   
public class Student { 
   
    @JsonProperty("name") 
    private String trueName; 
   
    public String getTrueName() { 
        return trueName; 
    } 
   
    public void setTrueName(String trueName) { 
        this.trueName = trueName; 
    } 
} 

测试一下:

import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.ObjectMapper; 
   
public class Main { 
    public static void main(String[] args) throws JsonProcessingException { 
        Student student = new Student(); 
        student.setTrueName("张三"); 
        System.out.println(new ObjectMapper().writeValueAsString(student)); 
    } 
} 

得到结果:

{"name":"张三"} 

注意:@JsonProperty不仅仅是在序列化的时候有用,反序列化的时候也有用,比如有些接口返回的是json字符串,命名又不是标准的驼峰形式,在映射成对象的时候,将类的属性上加上@JsonProperty注解,
里面写上返回的json串对应的名字。

@JsonIgnore使用:
在Student对象序列化为json数据的返回的时候,忽略该属性。代码及测试如下:

 @JsonProperty(value="real_name")
   private String name ;
   
   @JsonIgnore
   private String idCard;

Postman测试如下(条件:正常输入real_name和idCard,观察返回数据,只包含real_name)
在这里插入图片描述
@NotFound(action=NotFoundAction.IGNORE) 使用:
在many-to-one,one-to-one等关联中,一边引用自另一边的属性,如果属性值为某某的数据在数据库不存在了,hibernate默认会抛出异常。解决此问题,加上如下注解就可以了:
@NotFound(action=NotFoundAction.IGNORE),意思是找不到引用的外键数据时忽略,NotFound默认是exception

@JoinColumn 注解的作用
用来指定与所操作实体或实体集合相关联的数据库表中的列字段。

@JsonInclude(JsonInclude.Include.NON_NULL)
注解的作用是序列化json时,如果是null对象,key也会消失

JSR 提供的校验注解 :
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max=, min=) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式

使用 spring validation 完成数据后端校验:
Hibernate Validator 提供的校验注解 :
@NotBlank(message =) 验证字符串非 null,且长度必须大于 0
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
参考:https://www.cnkirito.moe/spring-validation/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值