当前位置:网站首页>JSON common annotations
JSON common annotations
2022-07-30 14:41:00 【Charm Lemon】
一、介绍
1、前言
在使用Java开发时,一定会接触到Json,The choice of front-end and back-end development is usedJson进行数据传输,and dealing with databasesBean类,I believe you must have encountered troubles caused by different field types,And using these annotations can be very convenient字段转换、字段忽略等等
这里我使用Spring自带的Jackson和阿里巴巴的FastJson作为记录
2、依赖引入
JacksonPackages depend on by defaultspring-boot-starter-web下,如果需要使用FastJson包,The original one needs to be removedJson依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.1</version>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-json</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.1</version>
</dependency>
二、Jackson常用注解
1、@JsonIgnoreProperties
类别:类注解
作用:json序列化时将bean中的一些属性忽略掉,Both serialization and deserialization are affected. Multiple properties can be written internally,Returning the frontend ignores this field
/** allowGetters,allowSetters一起用用来控制字段忽视是在序列化还是反序列化 allowGetters=true:Fields allow serialization,反序列的时候忽略该字段 allowSetters=true:Fields allow deserialization,序列化的时候忽略该字段 ignoreUnknown=true:Ignore unknown fields when deserializing,An error will be reported if the solution field cannot correspond to the entity classjson解析异常 */
@JsonIgnoreProperties({
"name"},{
"age"})
2、@JsonIgnore
类别:Annotations on properties or methods(最好是属性上)
作用:用来完全忽略被注解的字段和方法对应的属性,序列化和反序列化都受影响,Returning the frontend ignores this field
@JsonIgnore
private int age;
3、@JsonIgnoreType
类别:类注解
作用:Classes are ignored during serialization and deserialization,It is only ignored if the class is used as a property of another class,直接序列化、Deserializing the class is normal,Mainly used to ignore some data-sensitive objects,Such as the user's credentials
4、@JsonFormat
类别:used on properties or methods(最好是属性上)
作用:Add it to the attribute of the entity class corresponding to the database field whose time needs to be queried,It will be automatically formatted when returned,可以在属性对应的get方法上,两种方式没有区别
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date createTime;
// If you want to convert the front-end date string to Date格式 @DateTimeFormat(pattern="yyyy-MM-dd")
5、@JsonProperty
类别:用于属性
作用:Specify an attribute and json映射的名称
前端传过来的参数,Want to receive with another property name,This annotation can be added to properties
When the backend returns data to the frontend,Front-end requirements are specifiedkey,This annotation can be added to properties,will be in the annotationsvalue返回
public class User {
// In this way, the fields accepted by the front end are user_name
@JsonProperty("user_name")
private String userName;
}
6、@Transient
类别:used on properties or methods(最好是属性上)
作用:Properties do not map with fields of database tables—该字段在数据库中不存在,而需要使用.实体类中使用了@Table注解后,想要添加表中不存在的字段,就要使用@Transient这个注解;同时还有transient关键字标记的成员变量不参与序列化过程.
7、@JsonSerialize
类别:for attributes orgetter方法,Embed custom code when serializing
作用:需要使用 using The attribute specifies the class that handles the parameter,该类需要继承 JsonSerializer 类,并重写 serialize(). 若使用了 Lombok You need to define your own get 方法.
@JsonSerialize(using = CustomDateSerialize.class)
public Date getDate() {
return date;
}
public class CustomDateSerialize extends JsonSerializer<Date> {
// 定义日期格式
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(simpleDateFormat.format(date));
}
}
8、@JsonDeserialize
类别:for attributes orsetter方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize
作用:需要使用 using The attribute specifies the class that handles the parameter,该类需要继承 JsonSerializer 类,并重写 serialize(). 若使用了 Lombok You need to define your own get 方法.
//Gender display on the front end"男 / 女";数据库中存储的是"1 / 0",对应的 Pojo 也是使用的 Integer 类型
@Data
public class Person implements Serializable {
private static final long serialVersionUID = 4346092911489022673L;
/** * 1 男,0 女 */
private Integer gender;
@JsonDeserialize(using = GenderJsonDeserializer.class)
public void setGender(Integer gender) {
this.gender = gender;
}
@JsonSerialize(using = GenderJsonSerializer.class)
public Integer getGender() {
return gender;
}
}
// JsonDeserializer 作用是:处理参数,It is encapsulated into the specified attribute according to the rules,通过 jsonParser.getText() 获取参数
public class GenderJsonDeserializer extends JsonDeserializer {
@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
if (ObjectUtils.isEmpty(jsonParser)) {
return null;
}
int gender = 0;
switch (jsonParser.getText()) {
// 通过getText获取参数
case "男":
gender = 1;
break;
case "女":
break;
default:
throw new RuntimeException("The gender passed in is an illegal character");
}
return gender;
}
}
//JsonSerializer 作用是:处理属性,It is encapsulated into the specified parameters according to the rules,通过valueGet attribute pass jsonGenerator.writeXxx() 写出参数
public class GenderJsonSerializer extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (o.equals(1)) {
jsonGenerator.writeString("男"); // 写出参数
} else if (o.equals(0)) {
jsonGenerator.writeString("女"); // 写出参数
}
}
}
9、Serialize other related solutions
9.1 @JsonPropertyOrder
在将 java pojo 对象序列化成为 json 字符串时,使用 @JsonPropertyOrder 可以指定属性在 json 字符串中的顺序
9.2 @JsonInclude
在将 java pojo 对象序列化成为 json 字符串时,使用 @JsonInclude 注解可以控制在哪些情况下才将被注解的属性转换成 json
ALWAYS :默认策略,任何情况下都序列化该字段
NON_NULL:Annotated fields are null不序列化
NON_ABSENT:Annotated fields are nullis not serialized
NON_EMPTY :Annotated fields are nullor empty to not serialize
NON_DEFAULT:Fields with default values are not serialized
CUSTOM:Custom exclude serialization rules,过滤器对象的 equals() The method is called with the value to serialize; Exclude if it returns true(即过滤掉)
USE_DEFAULTS:Pseudo values are used to indicate that higher-level defaults are meaningful,to avoid overwriting include values. 例如,If returns an attribute,This will use the default value of the class containing the property,如果有的话; If not defined for this,The global serialization contains the details.
9.3 @JsonGetter、@JsonSetter注解
@JsonGetter和@JsonSetter注解只能用在getter和setter方法上,Used to deserialize to the specified field name and serialize to the specified field name,可以替换上面的@JsonPropertycan also be replaced;
public class People {
private String username;
@JsonGetter("USERNAME")
public String getUsername() {
return username;
}
@JsonSetter("USERNAME")
public void setUsername(String username) {
this.username = username;
}
}
9.4 @JsonAnySetter和@JsonAnyGetter注解
@JsonAnySetterThe annotation is added when the corresponding attribute does not exist in the entity object during deserialization 注解,Properties that do not exist will be placedMap中去@JsonAnyGetterThe annotation is serializedMapWith this attribute you can add mapThe properties in are serialized to the specified string
public class People {
private String username;
private Map<String, String> properties;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JsonAnyGetter
public Map<String, String> getProperties() {
return properties;
}
@JsonAnySetter
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
}
三、FastJson常用注解
文档:https://www.w3cschool.cn/fastjson/fastjson-intro.html
官方文档:https://github.com/alibaba/fastjson/wiki/Quick-Start-CN
1、介绍
FastJson提供了4种注解,分别是@JSONType,@JSONCreator,@JSONField,@JSONPOJOBuilder
2、@JSONField
// 若属性是私有的,必须有set*方法.否则无法反序列化.
public @interface JSONField {
// 配置序列化和反序列化的顺序,1.1.42版本之后才⽀持
int ordinal() default 0;
// 指定字段的名称
String name() default "";
// 指定字段的格式,对⽇Period format has⽤
String format() default "";
// 是否序列化
boolean serialize() default true;
// 是否反序列化
boolean deserialize() default true;
}
@JSONField(ordinal =0) 序列化字段的顺序,默认是0
@JSONField(name = “”) 用于解决属性名和key不一致的情况,当前端传过来的字段名不一样的时候,我们可以在字段名上加上这个注解
@JSONField(format = “yyyy-MM-dd HH:mm:ss”) , 用在Date属性上,自动格式化日期
@JSONField(serialize = false) 是否要把这个字段序列化成JSON字符串,默认是true
@JSONField(deserialize = false) 字段是否需要进行反序列化,默认是true
3、@JSONType
Putting it on an entity class will only assemble the enumerated fields or exclude the enumerated member variables
//Do not serialize these two
@JSONType(ignores = {
"id", "sex"})
public class Pojo2
//Serialization only serializes these two properties
@JSONType(includes = {
"name", "sex"})
public class Pojo1
边栏推荐
- ccs软件的使用(靠谱挣钱的app软件)
- Eight years of testing experience, why was the leader criticized: the test documents you wrote are not as good as those of fresh graduates
- A simple change for problem, knapsack problem sets of shell
- Simple understanding of Precision, Recall, Accuracy, TP, TN, FP, FN
- 华为7年经验的软件测试总监,给所有想转行学软件测试的朋友几点建议
- CF780G Andryusha and Nervous Barriers
- selenium4+pyetsst+allure+pom进行自动化测试框架的最新设计
- Huawei's 7-year-experienced software testing director, gives some advice to all friends who want to change careers to learn software testing
- 桌面软件开发框架大赏
- 业内人士真心话:只会测试没有前途的,我慌了......
猜你喜欢

Start learning C language

00 testers of seasoning after nearly a year, whether to change careers or to learn the software testing students summarized the following heart advice

Meta首份元宇宙白皮书9大看点,瞄准80万亿美元市场

容器排序案例

国内数字藏品的乱象与未来

双碳目标下:农田温室气体排放模拟

Huawei's 7-year-experienced software testing director, gives some advice to all friends who want to change careers to learn software testing

深入浅出零钱兑换问题——背包问题的套壳

激光雷达点云语义分割论文阅读小结

LeetCode二叉树系列——102.二叉树的层序遍历
随机推荐
LeetCode二叉树系列——102.二叉树的层序遍历
Eight years of testing experience, why was the leader criticized: the test documents you wrote are not as good as those of fresh graduates
3年软件测试经验面试要求月薪22K,明显感觉他背了很多面试题...
MIMO雷达波形设计
浅析显卡市场的未来走向:现在可以抄底了吗?
以unity3d为例解读:游戏数据加密
Androd 跳转到google应用市场
六面蚂蚁金服,抗住面试官的狂轰乱炸,前来面试复盘
产品年度营销计划书
CVE-2022-33891 Apache Spark 命令注入复现
The website adds a live 2d kanban girl that can dress up and interact
MPSK抗噪声性能对比(即MPSK标准误码率曲线)
#第九章 子查询课后习题
为什么做软件测试一定要学自动化?谈谈我眼中自动化测试的价值
Understand Chisel language. 28. Chisel advanced finite state machine (2) - Mealy state machine and comparison with Moore state machine
selenium4+pyetsst+allure+pom进行自动化测试框架的最新设计
5. DOM
A simple change for problem, knapsack problem sets of shell
Teach you how to write an eye-catching software testing resume, if you don't receive an interview invitation, I will lose
Flask Framework - Flask-Mail Mail