JAVA 金额自动除以100,精确到分

package net.crisps.cloud.order.commons.staff.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;

1.编写一个工具类继承 JsonSerializer

@Component
public class MoneyUtils extends JsonSerializer<Long> {

@Override
public void serialize(Long aLong, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (Objects.nonNull(aLong)) {
String format = getString(aLong);
jsonGenerator.writeString(format);
} else {//这个分支不要忘记了,否则将不输出这个属性的值
aLong = 0L;
String format = getString(aLong);
jsonGenerator.writeString(format);
}
}

private String getString(Long aLong) {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(aLong.doubleValue() / 100);
}
}

2. 再返回的实体上加上注解

 

 

3. 然后看返回数据

 

 




posted @ 2021-04-01 19:03  历尽千帆归来任是少年  阅读(2401)  评论(0编辑  收藏  举报