在Spring Boot中自定义序列化的方法是实现org.springframework.core.serializer.Serializer
接口或org.springframework.core.serializer.SmartSerializer
接口。
Serializer
接口,需要实现serialize(Object object, OutputStream outputStream)
方法,该方法负责将对象序列化为字节数组并写入输出流。SmartSerializer
接口,除了实现serialize
方法外,还需要实现boolean canSerialize(Class<?> clazz, MediaType mediaType)
方法,该方法用于判断是否可以对指定的类进行序列化。在自定义序列化方法后,可以通过在Spring Boot的配置类中使用@Bean
注解将自定义的序列化器注入到Spring容器中,并通过配置文件配置使用该序列化器。
例如,使用Jackson库自定义JSON序列化的示例代码如下:
import org.springframework.core.serializer.Serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonJsonSerializer implements Serializer<Object> {
private final ObjectMapper objectMapper;
public JacksonJsonSerializer() {
this.objectMapper = new ObjectMapper();
}
@Override
public void serialize(Object object, OutputStream outputStream) throws IOException {
objectMapper.writeValue(outputStream, object);
}
}
然后,在Spring Boot的配置类中将该序列化器注入到Spring容器中:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@Configuration
public class MyConfig {
@Bean
public JacksonJsonSerializer jacksonJsonSerializer() {
return new JacksonJsonSerializer();
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(JacksonJsonSerializer serializer) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(serializer.objectMapper);
return converter;
}
}
最后,在配置文件中配置使用自定义的序列化器:
spring.http.converters.preferred-json-mapper=jacksonJsonSerializer