全局配置
java
复制代码
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* @author Lux Sun
* @date 2023/8/27
*/
@Configuration
public class MyObjectMapperConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 设置序列化时忽略为null的字段
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 注册自定义的BigDecimalSerializer
objectMapper.registerModule(new SimpleModule()
.addSerializer(BigDecimal.class, new BigDecimalSerializerConfig())
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializerConfig()));
return objectMapper;
}
}
BigDecimal 数据类型
java
复制代码
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.szqy.common.domain.basic.OpenTime;
import java.io.IOException;
import java.math.BigDecimal;
public class BigDecimalSerializerConfig extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value != null) {
// 设置保留两位小数,并保留末尾的".00"
Object currentValue = gen.getCurrentValue();
String formattedValue = value.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
if (currentValue instanceof OpenTime) {
// 设置保留两位小数,并去除末尾的".00"
formattedValue = value.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
}
gen.writeString(formattedValue);
}
}
}
LocalDateTime 数据类型
java
复制代码
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeSerializerConfig extends JsonSerializer<LocalDateTime> {
private final DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public void serialize(LocalDateTime dateTime, JsonGenerator generator, SerializerProvider sp)
throws IOException {
String formattedDateTime = dateTime.format(dateTimeFormat);
generator.writeString(formattedDateTime);
}
}