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;
相关推荐
无敌最俊朗@1 小时前
STL-vector面试剖析(面试复习4)
java·面试·职场和发展
PPPPickup1 小时前
easychat项目复盘---获取联系人列表,联系人详细,删除拉黑联系人
java·前端·javascript
LiamTuc2 小时前
Java构造函数
java·开发语言
长安er2 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
菜鸟plus+2 小时前
N+1查询
java·服务器·数据库
我要添砖java2 小时前
《JAVAEE》网络编程-什么是网络?
java·网络·java-ee
CoderYanger2 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节
菜鸟233号4 小时前
力扣513 找树左下角的值 java实现
java·数据结构·算法·leetcode
Neoest4 小时前
【EasyExcel 填坑日记】“Syntax error on token )“: 一次编译错误在逃 Runtime 的灵异事件
java·eclipse·编辑器
自在极意功。4 小时前
Web开发中的分层解耦
java·microsoft·web开发·解耦