首页 > 其他分享 >MappingJackson2HttpMessageConverter数据处理

MappingJackson2HttpMessageConverter数据处理

时间:2023-08-02 14:37:23浏览次数:41  
标签:springframework class new 数据处理 import 序列化 MappingJackson2HttpMessageConverter ob

主键用的雪花算法,值域超过了js的范围……

后端返回的日期字段总不是我想要的格式……

空值的字段就不要返回了,省点流量吧……

试试换成自己的MappingJackson2HttpMessageConverter呗

Talk is cheap, show you the code!

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class DefaultMvcConfig implements WebMvcConfigurer {

    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
        converters.add(jackson2HttpMessageConverter());
    }

    /**
     * 时间格式转换器,将Date类型统一转换为yyyy-MM-dd HH:mm:ss格式的字符串
     * 长整型转换成String
     * 忽略value为null时key的输出
     */
    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = serializingObjectMapper();
        // 序列化枚举值
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
        //忽略value为null时key的输出
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //序列化成json时,将所有的Long变成string,以解决js中的精度丢失。
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        converter.setObjectMapper(objectMapper);
        return converter;
    }

    /**
     * jackson2 json序列化 null字段输出为空串
     */
    private ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //序列化日期格式
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer());
        javaTimeModule.addSerializer(Date.class, new DateSerializer(false, simpleDateFormat));
        //反序列化日期格式
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer());
        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                String date = jsonParser.getText();
                try {
                    return simpleDateFormat.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        objectMapper.registerModule(javaTimeModule);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        return objectMapper;
    }


    /**
     * LocalDateTime序列化
     */
    private class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(DATETIME_FORMATTER));
        }
    }

    /**
     * LocalDateTime反序列化
     */
    private class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return LocalDateTime.parse(p.getValueAsString(), DATETIME_FORMATTER);
        }
    }

    /**
     * LocalDate序列化
     */
    private class LocalDateSerializer extends JsonSerializer<LocalDate> {

        @Override
        public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(DATE_FORMATTER));
        }
    }

    /**
     * LocalDate反序列化
     */
    private class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

        @Override
        public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return LocalDate.parse(p.getValueAsString(), DATE_FORMATTER);
        }
    }

    /**
     * LocalTime序列化
     */
    private class LocalTimeSerializer extends JsonSerializer<LocalTime> {

        @Override
        public void serialize(LocalTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.format(TIME_FORMATTER));
        }
    }

    /**
     * LocalTime反序列化
     */
    private class LocalTimeDeserializer extends JsonDeserializer<LocalTime> {

        @Override
        public LocalTime deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
            return LocalTime.parse(p.getValueAsString(), TIME_FORMATTER);
        }
    }
}

标签:springframework,class,new,数据处理,import,序列化,MappingJackson2HttpMessageConverter,ob
From: https://blog.51cto.com/u_15668812/6937877

相关文章

  • OpenFOAM中的场数据处理——postProcess
    转载自胡老师的公众号“CFD之道”在仿真秀上的文章:OpenFOAM|13场数据处理_代码&命令_求解技术_科普_OpenFOAM-仿真秀干货文章(fangzhenxiu.com)本文简单介绍OpenFOAM中postProcess的使用。在OpenFOAM中,可以使用程序 postProcess 对计算得到的基础结果数据进行处理以获取新的......
  • 高效Python-1提高数据处理效率的迫切需要
    1提高数据处理效率的迫切需要本章包括处理指数级增长的数据所面临的挑战传统计算架构与最新计算架构的比较Python在现代数据分析中的作用和不足提供高效Python计算解决方案的技术我们一直在以极快的速度从各种来源收集海量数据。无论目前是否有使用价值,这些数据都会被收集......
  • Vue3的响应式数据处理方式
    问题:data[0].tableId是undefined,但控制台可以打印出data[0]的值原因: Vue3的响应式数据处理方式导致的。Vue3使用了Proxy来实现响应式数据。当你访问一个响应式对象的属性时,Vue会在底层进行拦截,并返回响应式的值。这意味着,当你访问`data[0].TableId`时,Vue会返回......
  • 新数据处理缺失值结果
    总共有440633个特征缺失,数据为109525×72,去除特定缺失值再补0。前7列数据缺失值过万了。缺失值小于10的列共33列距离2.9欧式角37 缺失值小于2600的列数44行3.1,角度2.9 缺失值350060列距离2.79角度36 8列-44列欧式距离2.9,角度31 ......
  • 5分钟教你从爬虫到数据处理到图形化一个界面实现山西理科分数查学校-Python
    5分钟教你从爬虫到数据处理到图形化一个界面实现山西理科分数查学校-Python引言在高考结束后,学生们面临的一大挑战是如何根据自己的分数找到合适的大学。这是一个挑战性的任务,因为它涉及大量的数据和复杂的决策过程。大量的信息需要被过滤和解析,以便学生们能对可能的大学选择有......
  • 在pandas中使用Sql进行数据处理的方案
    importpandasaspdimportpandasqlaspscurrent=pd.read_csv("cur.csv")previous=pd.read_csv("pre.csv")sql="""selectc.`Unnamed:0`asname,c.sumascurrent,p.sumasprevious,(c.sum-p.sum)asdifffromcu......
  • 详解Python数据处理Pandas库
    pandas是Python中最受欢迎的数据处理和分析库之一,它提供了高效的数据结构和数据操作工具。本文将详细介绍pandas库的使用方法,包括数据导入与导出、数据查看和筛选、数据处理和分组操作等。通过代码示例和详细解释,帮助你全面了解和应用pandas库进行数据处理和分析。一、安装和导......
  • os: pv 命令 - 显示数据处理的进度条
    os:pv命令 - 显示数据处理的进度条    一、pv 命令 1、pv 命令功能:显示数据处理的进度条 2、pv 命令安装:sudo apt install -y  pvdnf install -y   pv 3、pv 命令说明:[wit@ontmp]$pv--hel......
  • 高速图像采集卡:基于TI DSP TMS320C6678、Xilinx K7 FPGA XC7K325T的高速数据处理核心
    基于TIDSPTMS320C6678、XilinxK7FPGAXC7K325T的高速数据处理核心板一、板卡概述该DSP+FPGA高速信号采集处理板由北京太速科技自主研发,包含一片TIDSPTMS320C6678和一片XilinxFPGAK7XC72K325T-1ffg900。包含1个千兆网口,1个FMCHPC接口。可搭配使用ADFM......
  • 界面控件DevExpress WPF数据编辑器,让数据处理更灵活!(一)
    界面控件DevExpressWPF编辑器库可以帮助用户提供直观的用户体验,具有无与伦比的运行时选项和灵活性。WPF数据编辑器提供了全面的掩码和数据验证支持,可以独立使用,也可以作为容器控件(如DevExpressWPFGrid和WPFTreeList)中的单元格编辑器使用。DevExpressWPF拥有120+个控件和库......