springboot学习(四十六) springboot中jackson特殊使用

2024-06-20 08:18

本文主要是介绍springboot学习(四十六) springboot中jackson特殊使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、全局时间配置
在application.yml中配置

spring:jackson:date-format: yyyy-MM-dd HH:mm:ss

或在application.properties中配置

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

实体中包含时间类型:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {private Integer id;private int age;private String name;private Date createTime;
}

测试controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type1")
public class JacksonType1Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
2、使用@JsonFormat为某个属性设置序列化方式
实体:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {private Integer id;private int age;private String name;@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss")private Date createTime;
}

测试controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type2")
public class JacksonType2Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
3、使用@JsonPropertyOrder调整属性的序列化顺序
实体:

/***** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
@JsonPropertyOrder(value={"name", "age"})
public class Model {private Integer id;private int age;private String name;private Date createTime;
}

controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type3")
public class JacksonType3Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
4、使用@JsonProperty修改属性名称
实体:

/***** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {private Integer id;private int age;//调整序列化的名称@JsonProperty("myName")private String name;private Date createTime;
}

controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type4")
public class JacksonType4Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
5、使用@JsonInclude使属性值为null不参与序列化
实体:

/***** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {@JsonInclude(value= JsonInclude.Include.NON_NULL)private Integer id;private int age;private String name;private Date createTime;
}

controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type5")
public class JacksonType5Controller {@GetMapping("/res")public Model res() {return Model.builder().age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
6、使用@JsonIgnore使某个属性不参与序列化
实体:

/***** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:06* @since jdk1.8*/
@Data
@Builder
public class Model {@JsonIgnoreprivate Integer id;private int age;private String name;private Date createTime;
}

controller:

/**** @author zhuquanwen* @vesion 1.0* @date 2021/6/14 14:08* @since jdk1.8*/
@RestController
@RequestMapping("/jackson/type6")
public class JacksonType6Controller {@GetMapping("/res")public Model res() {return Model.builder().id(1).age(12).name("xiaoxiao").createTime(new Date()).build();}
}

测试结果:
在这里插入图片描述
7、自定义注解实现序列化和反序列化

将字符串转为数组的序列化处理

package com.iscas.base.biz.test.service;import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.iscas.common.web.tools.json.JsonUtils;import java.io.IOException;
import java.util.List;
import java.util.Objects;/*** @author zhuquanwen* @version 1.0* @date 2022/6/6 14:04* @since jdk11*/
public class CustomSerialize extends JsonSerializer<String> implements ContextualSerializer {@Overridepublic void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {if (value == null) {gen.writeNull();} else {TypeReference<List<String>> typeReference = new TypeReference<>() {};gen.writeObject(JsonUtils.fromJson(value, typeReference));}}@Overridepublic JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {//判断beanProperty是不是空if (property == null){return prov.findNullValueSerializer(property);}//判断类型是否是Stringif (Objects.equals(property.getType().getRawClass(),String.class)){CustomStrFormatter annotation = property.getAnnotation(CustomStrFormatter.class);if (annotation != null){// 这里可以获取注解中的一些参数String pattern = annotation.pattern();return this;}}return prov.findValueSerializer (property.getType (), property);}
}

将数组反序列化为JSON字符串的处理

package com.iscas.base.biz.test.service;import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.iscas.common.web.tools.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;import java.util.ArrayList;
import java.util.List;
import java.util.Objects;/*** @author zhuquanwen* @version 1.0* @date 2022/6/6 14:04* @since jdk11*/
public class CustomDeserialize extends JsonDeserializer<String> implements ContextualDeserializer {@Overridepublic String deserialize(JsonParser p, DeserializationContext ctxt) {try {if (p != null && StringUtils.isNotEmpty(p.getText())) {List<String> strs = new ArrayList<>();JsonToken jsonToken;while (!p.isClosed() && (jsonToken = p.nextToken()) != null && !JsonToken.FIELD_NAME.equals(jsonToken) &&!JsonToken.END_ARRAY.equals(jsonToken)) {strs.add(p.getValueAsString());}return JsonUtils.toJson(strs);} else {return null;}} catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {//判断beanProperty是不是空if (property == null) {return ctxt.findNonContextualValueDeserializer(property.getType());}//判断类型是否是Stringif (Objects.equals(property.getType().getRawClass(), String.class)) {CustomStrFormatter annotation = property.getAnnotation(CustomStrFormatter.class);if (annotation != null) {// 这里可以获取注解中的一些参数String pattern = annotation.pattern();return this;}}return ctxt.findContextualValueDeserializer(property.getType(), property);}
}

自定义注解

package com.iscas.base.biz.test.service;import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;/*** @author zhuquanwen* @version 1.0* @date 2022/6/6 14:02* @since jdk11*/
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = CustomSerialize.class)
@JsonDeserialize(using = CustomDeserialize.class)
public @interface CustomStrFormatter {// todo 可以定义格式化方式String pattern() default "";
}

实体中使用自定义注解

  @Data@Accessors(chain = true)public static class TestModel {private String id;private List<String> strs1;@CustomStrFormatterprivate String strs2;}

测试:

@RequestMapping("/test/serial")
@RestController
@Slf4j
public class TestJsonFormatterController {/*** 测试序列化* */@GetMappingpublic TestModel test1() {TestModel testModel = new TestModel();testModel.setId("1").setStrs1(List.of("1", "2", "3")).setStrs2("[\"3\", \"4\"]");return testModel;}@PostMappingpublic String test2(@RequestBody TestModel testModel) {log.info("接收到的testModel:{}", testModel.toString());return "success";}
}

这篇关于springboot学习(四十六) springboot中jackson特殊使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取