资讯动态

15 Jackson- JSON 处理自动配置

发布时间:2026/10/15 4:30:30 来源:尧图企业网站定制
1 介绍 Jacksonspring-boot-starter-web默认传递依赖 jackson-annotations具有JSON序列化和反序列化能力。spring-boot-starter-json 本身不是一套全新的 JSON 库而是 Spring Boot 提供的 JSON 处理自动配置 Starter。它默认集成 Jackson负责把 Java 对象自动转成 JSON、把 JSON 自动转回 Java 对象并提供全局配置、自定义序列化器、Mixin 等扩展能力。功能说明典型使用自动配置 JSON 映射器默认引入 Jackson自动注册JsonMapper/ObjectMapper不需要手动new ObjectMapper()请求反序列化把 JSON 请求体转成 Java 对象RequestBody User user响应序列化把 Java 对象转成 JSON 响应ResponseBody或RestController注解控制字段控制字段名、忽略、空值、日期格式等JsonProperty、JsonIgnore、JsonFormat全局配置通过application.yml或配置类统一调整行为spring.jackson.*自定义序列化/反序列化扩展处理复杂类型、特殊格式JacksonComponent、JsonSerializerMixin 支持不能修改源码时给第三方类附加 JSON 注解JacksonMixin2 JSON 请求体转成 Java 对象–请求反序列化RequestBody User userRestControllerRequestMapping(/users)publicclassUserController{PostMappingpublicUserRequestcreateUser(RequestBodyUserRequestrequest){//请求中的request JOSN 反转化为对象}}3 Java 对象转成 JSON 响应–响应序列化ResponseBody 或 RestControllerRestControllerRequestMapping(/users)publicclassUserController{PostMappingpublicUserRequestcreateUser(){// request反序列化为JOSN返回给前端returnrequest;}}4 常用注解JsonProperty:序列化和反序列化时把 Java 字段 name 映射为 JSON 中的字段名 product_name。JsonIgnore: 不参与序列化JsonFormat序列化和反序列化时转化日期为固定格式。JsonIncludeNON_NULL值为 null 时不序列化null、空字符串、空集合、空数组等不序列化NON_EMPTY通过自定义过滤器决定是否序列化CUSTOMpublicclassProduct{privateLongid;JsonProperty(product_name)privateStringname;JsonIgnoreprivateStringinternalCode;JsonFormat(patternyyyy-MM-dd)privateLocalDatepublishDate;JsonInclude(JsonInclude.Include.NON_NULL)privateStringdescription;}5 全局配置每次 JSON 序列化/反序列化时自动调用spring:jackson:date-format:yyyy-MM-dd HH:mm:sstime-zone:GMT8default-property-inclusion:non_nullserialization:indent-output:falsewrite-dates-as-timestamps:falsedeserialization:fail-on-unknown-properties:false6 自定义序列化/反序列化JacksonComponent、JsonSerializer6.1 方式一在字段上显式指定推荐publicclassUser{privateLongid;privateStringname;JsonSerialize(usingPhoneJsonSerializer.class)// 只脱敏这个字段privateStringphone;}序列化器本身不需要 JsonComponentpublicclassPhoneJsonSerializerextendsJsonSerializerString{Overridepublicvoidserialize(Stringvalue,JsonGeneratorgen,SerializerProviderserializers)throwsIOException{if(valuenull||value.length()11){gen.writeString(value);return;}Stringmaskedvalue.substring(0,3)****value.substring(7);gen.writeString(masked);}}6.2 方式二自定义类型 自动注册自动处理PhoneNumber 类型数据的序列化和反序列化JsonComponentpublicclassPhoneNumberSerializerextendsJsonSerializerPhoneNumber{Overridepublicvoidserialize(PhoneNumbervalue,JsonGeneratorgen,SerializerProviderserializers)throwsIOException{Stringphonevalue.getValue();if(phonenull||phone.length()11){gen.writeString(phone);return;}gen.writeString(phone.substring(0,3)****phone.substring(7));}}

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑