Jackson处理序列化转换的方式
细粒度,范围具体字段 @JsonSerialize
指定当前字段使用 ToStringSerializer 序列化
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
作用范围,根据字段命名或类型
指定范围Long类型转换为String
public class Long2StringJacksonConverter extends JsonSerializer<Long> {
@Override
public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// currentName 为当前字段名
String currentName = jsonGenerator.getOutputContext().getCurrentName();
String text = (value == null ? null : String.valueOf(value));
if (text != null) {
jsonGenerator.writeString(text);
}
}
// 指定转换器所属类型,key为class类型
@Override
public Class<Long> handledType() {
return Long.class;
}
}
jackson2ObjectMapperFactoryBean 注册序列化
@Configuration
public class ConverterConfig {
@Bean
public DateJacksonConverter dateJacksonConverter() {
return new DateJacksonConverter();
}
@Bean
public Long2StringJacksonConverter long2StringJacksonConverter() {
return new Long2StringJacksonConverter();
}
@Bean
public Jackson2ObjectMapperFactoryBean jackson2ObjectMapperFactoryBean(
@Autowired
Long2StringJacksonConverter long2StringJacksonConverter) {
Jackson2ObjectMapperFactoryBean jackson2ObjectMapperFactoryBean = new Jackson2ObjectMapperFactoryBean();
jackson2ObjectMapperFactoryBean.setSerializers(long2StringJacksonConverter);
return jackson2ObjectMapperFactoryBean;
}
}
全局转换 ObjectMapper
ObjectMapper 注册 module 模块
@Configuration
public class ConverterConfig {
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(
@Autowired
ObjectMapper objectMapper) {
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter =
new MappingJackson2HttpMessageConverter();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
return mappingJackson2HttpMessageConverter;
}
}
jackson2 应用全局配置
Jackson2ObjectMapperBuilderCustomizer 自定义 ObjectMapper 建造其器
@Configuration
public class JacksonConfig {
/**
* Jackson全局转化long类型为String,解决jackson序列化时long类型缺失精度问题
* @return Jackson2ObjectMapperBuilderCustomizer 注入的对象
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
Jackson2ObjectMapperBuilderCustomizer cunstomizer = new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringSerializer.instance);
jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
}
};
return cunstomizer;
}
|