Jackson 2.x 系列【5】注解大全篇一

2024-03-29 06:52
文章标签 系列 注解 jackson 全篇

本文主要是介绍Jackson 2.x 系列【5】注解大全篇一,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

有道无术,术尚可求,有术无道,止于术。

本系列Jackson 版本 2.17.0

源码地址:https://gitee.com/pearl-organization/study-jackson-demo

文章目录

    • 1. 前言
    • 2. 注解大全
      • 2.1 @JsonIgnore
      • 2.2 @JsonFormat
      • 2.3 @JsonInclude
      • 2.4 @JsonProperty
      • 2.5 @JsonAlias
      • 2.6 @JsonIgnoreType
      • 2.7 @JsonIgnoreProperties
      • 2.8 @JsonPropertyOrder
      • 2.9 @JsonGetter
      • 2.10 @JsonSetter

1. 前言

在前几篇文档中,我们学习了Jackson中几个非常重要的类,并实现了一些简单的JSON数据转换功能。在实际开发中,可能会遇到的一些个性化要求的场景,而不是简单的一些直接转换,例如,对于null值字段、敏感字段不进行序列化;Long类型的字段需要序列化为String类型(不然返回给前端时会丢失精度)…

Jackson提供了两种方式来满足个性化场景,以定制序列化/反序列化行为:

  • 配置注解Jackson提供了很多注解,用于标识Java Bean类、方法、构造器、属性
  • 配置特性枚举Jackson提供了很多xxxFeature枚举类,在读写对象中进行设置

⛹⛹⛹接下来我们了解下Jackson提供的所有注解,按照它们的使用频率顺序进行讲解。⛹⛹⛹

2. 注解大全

Jackson中的大部分注解都在jackson-annotations模块中,位于com.fasterxml.jackson.annotation包下,在jackson-databind模块中也提供了一些注解。

2.1 @JsonIgnore

@JsonIgnore标识序列化/反序列化时是否忽略该字段。

@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonIgnore {// 是否忽略,默认trueboolean value() default true;
}

UserInfo类的id属性添加 @JsonIgnore

public class UserInfo{@JsonIgnore// 用户IDprivate Long id;// 省略其他......
}

进行转换:

        ObjectMapper objectMapper = new ObjectMapper();// POJO -> JSONUserInfo user = new UserInfo();user.setId(1767798780627279333L);user.setName("老三");user.setAge(25);String json = objectMapper.writeValueAsString(user);System.out.println(json);// JSON -> POJOString userJson="{\"id\":1767798780627279873,\"name\":\"坤坤\",\"age\":18,\"org\":null,\"roleList\":null}";UserInfo readUserByJson = objectMapper.readValue(userJson, UserInfo.class);System.out.println(readUserByJson);

可以看到id字段被忽略了:

{"name":"老三","age":25,"org":null,"roleList":null}
UserInfo{id=null, name='坤坤', age=18, org=null, roleList=null}

2.2 @JsonFormat

@JsonFormat标识使用格式模板进行序列化/反序列化

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonFormat {// 默认的 Locale,java.util.Locale#getDefault()String DEFAULT_LOCALE = "##default";// 默认的 时区,来自于  java.util.TimeZoneString DEFAULT_TIMEZONE = "##default";// 格式模板String pattern() default "";// 指定序列化后的类型Shape shape() default JsonFormat.Shape.ANY;// Java Locale String locale() default "##default";// 时区String timezone() default "##default";// 是否启用“宽松”处理OptBoolean lenient() default OptBoolean.DEFAULT;// 开启某些特性Feature[] with() default {};// 关闭某些特征Feature[] without() default {};// 省略其他......
}

UserInfo类的birthdayDate属性添加 @JsonFormat注解:

    @JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private Date birthdayDate;

序列化/反序列化结果:

{"id":1767798780627279333,"birthdayDate":"2024-03-21 09:40:33","birthdayLocalDateTime":null,"name":"老三","age":25,"org":null,"roleList":null}
UserInfo{id=1767798780627279333, birthdayDate=Thu Mar 21 09:40:33 CST 2024, birthdayLocalDateTime=null, name='老三', age=25, org=null, roleList=null}

UserInfo类的birthdayLocalDateTime属性添加 @JsonFormat注解:

    @JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private LocalDateTime birthdayLocalDateTime;

这时会报错InvalidDefinitionException,不支持java.time.LocalDateTime

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.pearl.jacksoncore.demo.databind.anno.UserInfo["birthdayLocalDateTime"])

LocalDateTimeJava 8JSR 310规范下新的日期时间APIJackson核心模块并没有实现支持,需要引入jackson-datatype-jsr310模块:

        <dependency><groupId>com.fasterxml.jackson.datatype</groupId><artifactId>jackson-datatype-jsr310</artifactId><version>2.17.0</version></dependency>

并指定序列化/反序列化器:

    @JsonDeserialize(using = LocalDateTimeDeserializer.class)@JsonSerialize(using = LocalDateTimeSerializer.class)@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private LocalDateTime birthdayLocalDateTime;

再次运行,结果如下:

{"id":1767798780627279333,"birthdayDate":"2024-03-21 09:47:59","birthdayLocalDateTime":"2024-03-21 09:47:59","name":"老三","age":25,"org":null,"roleList":null}
UserInfo{id=1767798780627279333, birthdayDate=Thu Mar 21 09:47:59 CST 2024, birthdayLocalDateTime=2024-03-21T09:47:59, name='老三', age=25, org=null, roleList=null}

2.3 @JsonInclude

@JsonFormat标识符合指定规格时才进行序列化

@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonInclude {//   规则://   ALWAYS, 总是序列化//   NON_NULL, 不为NULL才序列化//   NON_ABSENT, NON_NULL的基础上,支持 Optional//   NON_EMPTY,  NON_ABSENT的基础上,支持集合、String//   NON_DEFAULT, 不是默认值才序列化//   CUSTOM, 自定义//   USE_DEFAULTS; 默认//  作用于类、属性Include value() default JsonInclude.Include.ALWAYS;// 作用于 Map、AtomicReference等Include content() default JsonInclude.Include.ALWAYS;// 自定义规则需要实现的过滤器Class<?> valueFilter() default Void.class;// 自定义规则需要实现的过滤器Class<?> contentFilter() default Void.class;

UserInfo类的birthdayDate属性添加 @JsonFormat注解,配置规则为NON_NULL时才进行序列化:

    @JsonInclude(JsonInclude.Include.NON_NULL)private String name;

运行结果如下:

        user.setName(null);String JsonIncludeJson = objectMapper.writeValueAsString(user);System.out.println(JsonIncludeJson);// {"birthdayDate":"2024-03-21 11:00:23","birthdayLocalDateTime":"2024-03-21 11:00:23","age":25,"org":null,"roleList":null}

2.4 @JsonProperty

@JsonProperty用于在序列化/反序列化时进行重命名。

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonProperty {String USE_DEFAULT_NAME = "";int INDEX_UNKNOWN = -1;// 重命名后的属性名称String value() default "";String namespace() default "";boolean required() default false;// 索引位置int index() default -1;String defaultValue() default "";// 可见性配置 可以控制只在序列化或者只反序列化时生效Access access() default JsonProperty.Access.AUTO;public static enum Access {// 自动确定对此属性的读/或访问权限AUTO,// 只读READ_ONLY,// 只写WRITE_ONLY,// 可读写READ_WRITE;}
}

UserInfo类的age属性添加 @JsonProperty注解:

    @JsonProperty(value = "userAge")private Integer age;

序列化后结果:

{"userAge":25,"birthdayDate":"2024-03-21 11:43:25","birthdayLocalDateTime":"2024-03-21 11:43:25","org":null,"roleList":null}

2.5 @JsonAlias

@JsonAlias用于在反序列化时进行重命名。

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonAlias {String[] value() default {};
}

例如JSON中属性名称为usernameUserInfo类中的属性名称为name,则可以使用@JsonAlias指定反序列化时的别名:

    @JsonAlias("username")private String name;

示例如下:

        String userAliasJson="{\"id\":1767798780627279873,\"username\":\"坤坤\",\"userAge\":18,\"org\":null,\"roleList\":null}";UserInfo readUserByAliasJson = objectMapper.readValue(userAliasJson, UserInfo.class);System.out.println(readUserByAliasJson);// UserInfo{id=null, birthdayDate=null, birthdayLocalDateTime=null, name='坤坤', age=18, org=null, roleList=null}

2.6 @JsonIgnoreType

@JsonIgnoreType作用于类,当该类作为对象属性在序列化/反序列化时会被忽略。

@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonIgnoreType {// 是否忽略,默认 tureboolean value() default true;
}

例如我们在Org类中添加该注解:

@JsonIgnoreType
public class Org {// 省略.....}

执行反序列化:

        // 6. @JsonIgnoreTypeString userJsonIgnoreTypeStr="{\"id\":1767798780627279873,\"username\":\"坤坤\",\"userAge\":18,\"org\":{\"id\":1699967647585800192,\"orgName\":\"阿里巴巴\",\"address\":\"浙江杭州\"},\"roleList\":null}";UserInfo readUserByJsonIgnoreType = objectMapper.readValue(userJsonIgnoreTypeStr, UserInfo.class);System.out.println(readUserByJsonIgnoreType);

虽然JSON内容包含了Org对象,但是被忽略掉了:

UserInfo{id=null, birthdayDate=null, birthdayLocalDateTime=null, name='坤坤', age=18, org=null, roleList=null}

2.7 @JsonIgnoreProperties

@JsonIgnoreProperties用于在序列化/反序列化时忽略某个字段属性,比@JsonIgnore功能更强,可以作用于类,配置多个忽略属性。

@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonIgnoreProperties {// 忽略的多个属性名称String[] value() default {};// 是否忽略不能识别的属性boolean ignoreUnknown() default false;// 是否允许访问属性的Getter方法,即支持Getter进行序列化boolean allowGetters() default false;// 是否允许访问属性的Setters方法,即支持Setters进行反序列化boolean allowSetters() default false;
}

Org类上标识忽略idorgName属性:

@JsonIgnoreProperties({"orgName","id"})
public class Org {// 省略.....}

案例演示,当前JSON包含了idorgName属性:

        String userIgnorePropertiesStr="{\"id\":1767798780627279873,\"username\":\"坤坤\",\"userAge\":18,\"org\":{\"id\":1699967647585800192,\"orgName\":\"阿里巴巴\",\"address\":\"浙江杭州\"},\"roleList\":null}";UserInfo readUserByIgnoreProperties = objectMapper.readValue(userIgnorePropertiesStr, UserInfo.class);System.out.println(readUserByIgnoreProperties);

反序列化时idorgName属性被忽略:

UserInfo{id=null, birthdayDate=null, birthdayLocalDateTime=null, name='坤坤', age=18, org=Org{id=null, orgName='null', address='浙江杭州'}, roleList=null}

之外还支持allowGetters 配置可以进行序列化,但反序列化时被忽略(allowSetters同理):

@JsonIgnoreProperties( value = "password",allowGetters = true)

2.8 @JsonPropertyOrder

@JsonPropertyOrder用于在序列化时进行排序。

@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonPropertyOrder {// 指定顺序String[] value() default {};// 是否按照字母表排序boolean alphabetic() default false;
}

示例代码:

@JsonPropertyOrder({"org","roleList","birthdayDate","id"})

输出结果:

{"org":null,"roleList":null,"birthdayDate":"2024-03-21 14:44:49","birthdayLocalDateTime":"2024-03-21 14:44:49","password":null,"userAge":25}

2.9 @JsonGetter

@JsonGetter@JsonProperty功能类似用于重命名,官方提示使用其替代方案@JsonProperty

@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonGetter {String value() default "";
}

示例代码:

    @JsonGetter("userSex")public String getSex() {return sex;}

可以看到在序列化/反序列化时都会生效,一般使用@JsonProperty即可:

        user.setSex("男");String jsonGettersStr = objectMapper.writeValueAsString(user);System.out.println(jsonGettersStr);String jsonGetterStr="{\"userSex\":\"男\",\"id\":1767798780627279873,\"username\":\"坤坤\",\"userAge\":18,\"org\":{\"id\":1699967647585800192,\"orgName\":\"阿里巴巴\",\"address\":\"浙江杭州\"},\"roleList\":null}";UserInfo readUserByJsonGetter = objectMapper.readValue(jsonGetterStr, UserInfo.class);System.out.println(readUserByJsonGetter);

2.10 @JsonSetter

@JsonSetter@JsonProperty功能类似用于重命名,官方提示使用其替代方案@JsonProperty

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonSetter {String value() default "";Nulls nulls() default Nulls.DEFAULT;Nulls contentNulls() default Nulls.DEFAULT;

示例代码:

    @JsonSetter("mobilePhone")public void setPhone(String phone) {this.phone = phone;}

可以看到在序列化/反序列化时都会生效:

        user.setPhone("13899996666");String jsonSettersStr = objectMapper.writeValueAsString(user);System.out.println(jsonSettersStr);String jsonSetterStr="{\"mobilePhone\":\"13899996666\",\"userSex\":\"男\",\"id\":1767798780627279873,\"username\":\"坤坤\",\"userAge\":18,\"org\":{\"id\":1699967647585800192,\"orgName\":\"阿里巴巴\",\"address\":\"浙江杭州\"},\"roleList\":null}";UserInfo readUserByJsoSetter = objectMapper.readValue(jsonSetterStr, UserInfo.class);System.out.println(readUserByJsoSetter);

这篇关于Jackson 2.x 系列【5】注解大全篇一的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/857904

相关文章

Spring Boot/Spring MVC核心注解的作用详解

《SpringBoot/SpringMVC核心注解的作用详解》本文详细介绍了SpringBoot和SpringMVC中最常用的15个核心注解,涵盖了请求路由映射、参数绑定、RESTfulAPI、... 目录一、Spring/Spring MVC注解的核心作用二、请求映射与RESTful API注解系列2.1

Springmvc常用的注解代码示例

《Springmvc常用的注解代码示例》本文介绍了SpringMVC中常用的控制器和请求映射注解,包括@Controller、@RequestMapping等,以及请求参数绑定注解,如@Request... 目录一、控制器与请求映射注解二、请求参数绑定注解三、其他常用注解(扩展)四、注解使用注意事项一、控制

Spring Boot整合Redis注解实现增删改查功能(Redis注解使用)

《SpringBoot整合Redis注解实现增删改查功能(Redis注解使用)》文章介绍了如何使用SpringBoot整合Redis注解实现增删改查功能,包括配置、实体类、Repository、Se... 目录配置Redis连接定义实体类创建Repository接口增删改查操作示例插入数据查询数据删除数据更

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

Spring的基础事务注解@Transactional作用解读

《Spring的基础事务注解@Transactional作用解读》文章介绍了Spring框架中的事务管理,核心注解@Transactional用于声明事务,支持传播机制、隔离级别等配置,结合@Tran... 目录一、事务管理基础1.1 Spring事务的核心注解1.2 注解属性详解1.3 实现原理二、事务事

Java JDK Validation 注解解析与使用方法验证

《JavaJDKValidation注解解析与使用方法验证》JakartaValidation提供了一种声明式、标准化的方式来验证Java对象,与框架无关,可以方便地集成到各种Java应用中,... 目录核心概念1. 主要注解基本约束注解其他常用注解2. 核心接口使用方法1. 基本使用添加依赖 (Maven

SpringBoot AspectJ切面配合自定义注解实现权限校验的示例详解

《SpringBootAspectJ切面配合自定义注解实现权限校验的示例详解》本文章介绍了如何通过创建自定义的权限校验注解,配合AspectJ切面拦截注解实现权限校验,本文结合实例代码给大家介绍的非... 目录1. 创建权限校验注解2. 创建ASPectJ切面拦截注解校验权限3. 用法示例A. 参考文章本文

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

Java利用@SneakyThrows注解提升异常处理效率详解

《Java利用@SneakyThrows注解提升异常处理效率详解》这篇文章将深度剖析@SneakyThrows的原理,用法,适用场景以及隐藏的陷阱,看看它如何让Java异常处理效率飙升50%,感兴趣的... 目录前言一、检查型异常的“诅咒”:为什么Java开发者讨厌它1.1 检查型异常的痛点1.2 为什么说