SpringBoot | Jackson序列化
  QNyb8JwuOaZo 2023年11月19日 39 0

Spring MVC 默认采用Jackson解析Json,尽管还有一些其它同样优秀的json解析工具,例如Fast Json、GSON,但是出于最小依赖的考虑,也许Json解析第一选择就应该是Jackson。

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

依赖

<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消息转换器

@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;
    }
}



【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月19日 0

暂无评论

推荐阅读
QNyb8JwuOaZo