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;
相关推荐
callJJ4 分钟前
JVM 类加载机制详解——从 .class 文件到对象诞生的完整旅程
java·jvm·类加载·双亲委派模型
Kiling_070418 分钟前
Java Math类核心用法全解析
java·开发语言
踏着七彩祥云的小丑18 分钟前
开发中用到的注解
java
小梦爱安全20 分钟前
Ansible剧本1
java·网络·ansible
pupudawang44 分钟前
Spring Boot 热部署
java·spring boot·后端
我登哥MVP1 小时前
【SpringMVC笔记】 - 9 - 异常处理器
java·spring boot·spring·servlet·tomcat·maven
下地种菜小叶1 小时前
Spring Boot 2.x 升级 3.x / 4.x 怎么做?一次讲清 JDK、Jakarta、依赖兼容与上线策略
java·spring boot·后端
iiiiyu1 小时前
常用API(StringJoiner类 & Math类 & System类)
java·大数据·开发语言·数据结构·编程语言
有梦想的小何1 小时前
`Java并发排障实录:没有报错,却把正确数据覆盖错了`
java·spring boot·mysql·spring cloud
Xiu Yan1 小时前
Java 转 C++ 系列:函数对象、谓词和内建函数对象
java·开发语言·c++