**
* 描述:金额数值序列化
* 1.分 -> 万 当前数据除以6个0: 1000000 -> 1
*
*/
public class Object6Serialize extends JsonSerializer<Object> {
//修改要除的数据
private static final BigDecimal TEMP = BigDecimal.valueOf(1000000L);
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value != null) {
BigDecimal bigDecimal = new BigDecimal(value.toString());
//参考该方法 第二个参数是几就保留几位小数 第三个参数 参考 RoundingMode.java
gen.writeNumber(bigDecimal.divide(TEMP, 4, RoundingMode.DOWN));
}
}
}
使用
@Data
public class ValuationAmountVo {
@JsonSerialize(using = Object6Serialize.class)
private double valuation;
@JsonSerialize(using = Object6Serialize.class)
private double amount;
}
@ApiOperation(value = "数据转换接口")
@ApiImplicitParam(name = "number", value = "输入的数据进行转换", required = true, example = "123456789")
@GetMapping(value = "numberSerialize")
public CommonResponse numberSerialize(@RequestParam("number") Long number) {
NumberVO numberVO = new NumberVO();
numberVO.setNumber(number);
return success(numberVO);
}
接口出参 在debug时数据不会被转换,接口结束时才会被转换 ,数据传输过程中不会被转换
测试:建议用swagger 查看
--以下是比较老的版本了:时间是:
1.编写注解使用的类
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DoubleSerialize extends JsonSerializer<Double> {
private DecimalFormat df = new DecimalFormat("0.00");
@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
if(value != null) {
df.setMaximumFractionDigits(2);//显示几位修改几
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.FLOOR);
//根据实际情况选择使用
// gen.writeString(df.format(value)); // 返回出去是字符串
gen.writeNumber(df.format(value)); // 返回出去是数字形式 2018年12月27日17:17:21 更新
}
}
}
2.在需要被注解修改的数据上调用
@Data
public class ValuationAmountVo {
@JsonSerialize(using = DoubleSerialize.class)
private double valuation;
@JsonSerialize(using = DoubleSerialize.class)
private double amount;
}
🐞标题:添加json注解解决返回数据double限定小数点后几位长度,多余的舍弃
👽作者:ruige
🐾地址:https://jjdhhc.com/articles/2020/11/07/1604719832354.html
🙏感恩:谢谢您的打赏与支持!中间图片是我的微信公众号,扫码关注哦!