SpringBoot | Jackson序列化

欢迎参观我的博客,一个Vue 与 SpringBoot结合的产物:https://poetize.cn#

原文链接:https://poetize.cn/article?id=37

依赖#

Copy
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency>

Jackson注解#

  • @JsonProperty("name"):把该属性名称序列化为另外一个名称
  • @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8"):序列化时间为指定格式
  • @JsonIgnore:进行JSON操作时忽略该属性
  • @JsonInclude(JsonInclude.Include.NON_NULL):序列化仅包含非NULL属性

SpringBoot的Json消息转换器#

Copy
@Configuration public class WebConfig implements WebMvcConfigurer { /** * MappingJackson2HttpMessageConverter是一个Spring消息转换器,用于在Web应用程序中处理请求和响应内容。 */ @Bean public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); //设置日期格式 objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); objectMapper.setTimeZone(TimeZone.getDefault()); //所有字段都序列化,包括空、NULL、默认值 objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); //BigDecimal对象的值将以纯文本形式写入JSON,即不会使用科学计数法或其他格式来表示。 objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true); //序列化对象为 JSON 时,是否忽略那些在目标 JSON 中没有对应字段名的属性。 objectMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true); //反序列化(将 JSON 转换为 Java 对象)时,是否在 JSON 中存在但在目标 Java 类中没有相应属性时引发异常。 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //返回Long转换为String SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); simpleModule.addSerializer(long.class, ToStringSerializer.instance); objectMapper.registerModule(simpleModule); mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper); //设置中文编码格式 List<MediaType> list = new ArrayList<>(); list.add(MediaType.APPLICATION_JSON); mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list); return mappingJackson2HttpMessageConverter; } }
posted @   LittleDonkey  阅读(254)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示
CONTENTS