添加json注解解决返回数据double限定⼩数点后⼏位长度,多
余的舍弃
--更新 2019年6⽉14⽇19:52:13
**
* 描述:⾦额数值序列化
* 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 String());
//参考该⽅法第⼆个参数是⼏就保留⼏位⼩数第三个参数参考 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 = "数据转换接⼝")
bigdecimal除法保留小数@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.JsonGenerator;
import com.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.math.RoundingMode;
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;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论