Spring 序列化与反序列化

Spring 默认使用 Jackson 库来序列化和反序列化 JSON 数据。Jackson 是一个流行的 JSON 处理库,功能强大且易于使用,Spring 项目会自动配置 Jackson 来处理 JSON 数据的转换。

序列化配置
全局配置
复制代码
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 例如,启用pretty-printing
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // 其他配置...
        return mapper;
    }
}
自定义

序列化器

复制代码
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;

public class CustomSerializer extends JsonSerializer<MyClass> {

    @Override
    public void serialize(MyClass value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("customField", value.getCustomField());
        // 其他字段...
        gen.writeEndObject();
    }
}

反序列化器

复制代码
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;

public class CustomDeserializer extends JsonDeserializer<MyClass> {

    @Override
    public MyClass deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        // 自定义反序列化逻辑
        return new MyClass();
    }
}

注册

复制代码
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(MyClass.class, new CustomSerializer());
        module.addDeserializer(MyClass.class, new CustomDeserializer());
        mapper.registerModule(module);
        return mapper;
    }
}

或者,使用@JsonSerialize,@JsonDeserialize来序列化或反序列化

复制代码
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@JsonSerialize(using = CustomSerializer.class)
@JsonDeserialize(using = CustomDeserializer.class)
public class MyClass {
    // do something
}
序列化日期
方式一:全局配置日期格式
复制代码
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
方式二:使用@JsonFormat注解
复制代码
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date effectTime;
方式三:自定义 ObjectMapper 配置
复制代码
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return objectMapper;
    }
}
方式四:使用自定义的日期转换器
复制代码
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomDateDeserializer extends JsonDeserializer<Date> {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String date = p.getText();
        try {
            return dateFormat.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

使用

复制代码
@JsonDeserialize(using = CustomDateDeserializer.class)
private Date effectTime;
相关推荐
摇滚侠2 分钟前
《SpringBoot 3:入门与应用实战》第 15 章 生产级特性 监控指标 Metrics 阅读笔记
java·spring boot·笔记
弹简特28 分钟前
【Java项目-企悦抽】11-用户与认证模块-实现用户登录03(结束登录功能)-完成测试+对接前端+登录拦截器
java·开发语言
大模型丫丫1 小时前
Loop Engineering:从强化学习视角看 Agent 循环的本质
java·人工智能·学习
数电发票API1 小时前
税局接口,需要的来~~
java
骇客野人1 小时前
IntelliJ IDEA 使用技巧
java·ide·intellij-idea
Jul1en_2 小时前
【Java 脚手架】封装通用工具类-1
java·spring boot·分布式·spring·spring cloud
我命由我123452 小时前
Java 开发 - List subList 方法
java·windows·操作系统·list·intellij-idea·idea·intellij idea
关于不上作者榜就原神启动那件事2 小时前
从 MDC 到 Agent:我手搓的文档路由协议,在 Spring AI Alibaba 里找到了正式实现
java·人工智能·spring·ai·agent
亦暖筑序2 小时前
重新认识 AgentScope-Java 2.0:ReActAgent 负责推理,HarnessAgent 负责运行
java·后端·agent
木井巳3 小时前
【DFS解决floodfill算法】岛屿的最大面积
java·算法·leetcode·深度优先