jackson自定义序列化和反序列化
自定义序列化
序列化主要作用在返回数据的时候 以BigDecimal统一返回3位小数为例 自定义序列化处理类 继承jackson的JsonSerializer
类,重写serialize
方法
public class BigDecimalSerializer extends JsonSerializer < BigDecimal > { @Override public void serialize ( BigDecimal value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException { jsonGenerator. writeString ( formatBigDecimal ( value) ) ; } private String formatBigDecimal ( BigDecimal value) { if ( Objects . nonNull ( value) && value. compareTo ( BigDecimal . ZERO ) >= 0 ) { DecimalFormat df = new DecimalFormat ( ) ; df. applyPattern ( "0.000" ) ; return df. format ( value) ; } return null ; }
}
使用的时候,可以直接使用Jackson的@JsonSerialize
注解
@JsonSerialize ( using = BigDecimalSerializer . class ) private BigDecimal amount;
自定义反序列化
接收前端传入数据 继承JsonDeserializer
类,重写deserialize
方法 例子:后端传入前端的图片链接,去掉域名,只保存path部分
public class StaticUrlDeserialize extends JsonDeserializer < String > { @Override public String deserialize ( JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { String text = jsonParser. getText ( ) ; String domain = "https://domain/" ; String path = text. replace ( domain, "" ) ; return path; }
}
使用的时候,可以直接使用Jackson的@JsonDeserialize
注解
@ApiModelProperty ( value = "用户头像" , position = 6 ) @JsonDeserialize ( using = StaticUrlDeserialize . class ) private String avatar;
统一配置自定义序列化、反序列化
也可以使用全局统一配置 统一处理BigDecimal
返回格式和日期
@Configuration
public class JacksonConfig { @Bean public ObjectMapper ObjectMapper ( ) { ObjectMapper objectMapper = new ObjectMapper ( ) ; SimpleModule simpleModule = new SimpleModule ( ) ; simpleModule. addSerializer ( BigDecimal . class , new BigDecimalSerializer ( ) ) ; simpleModule. addSerializer ( LocalDateTime . class , new LocalDateTimeSerializer ( DateTimeFormatter . ofPattern ( "yyyy-MM-dd HH:mm:ss" ) ) ) ; simpleModule. addSerializer ( LocalDate . class , new LocalDateSerializer ( DateTimeFormatter . ofPattern ( "yyyy-MM-dd" ) ) ) ; simpleModule. addSerializer ( LocalTime . class , new LocalTimeSerializer ( DateTimeFormatter . ofPattern ( "HH:mm:ss" ) ) ) ; simpleModule. addDeserializer ( LocalDateTime . class , new LocalDateTimeDeserializer ( DateTimeFormatter . ofPattern ( "yyyy-MM-dd HH:mm:ss" ) ) ) ; simpleModule. addDeserializer ( LocalDate . class , new LocalDateDeserializer ( DateTimeFormatter . ofPattern ( "yyyy-MM-dd" ) ) ) ; simpleModule. addDeserializer ( LocalTime . class , new LocalTimeDeserializer ( DateTimeFormatter . ofPattern ( "HH:mm:ss" ) ) ) ; objectMapper. registerModule ( simpleModule) ; return objectMapper; }
}