1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import lombok.extern.slf4j.Slf4j;
import java.io.IOException; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Objects;
@Slf4j public class DoubleSerialize extends JsonSerializer {
private final DecimalFormat df = new DecimalFormat("0.0");
@Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { if (Objects.nonNull(o)) { df.setRoundingMode(RoundingMode.HALF_UP); String result = df.format(o); jsonGenerator.writeNumber(Double.parseDouble(result)); log.info("转换数字:" + Double.parseDouble(result)); } else { jsonGenerator.writeNumber(Double.valueOf(0)); } } }
|