在显示类上面添加@JsonSerialize注解,指定对应的转换格式例如,同理可在属性为BigDecimal的字段上添加注解,指定方法:
java
private String userTypeStr;
/**
* 交易金额
*/
@JsonSerialize(using = StringSerialize.class)
private String transAmount;
/**
* 交易账户
*/
private String transMerUserId;
对应的格式化代码类String 千分位:
java
import cn.hutool.core.util.StrUtil;
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.BigDecimal;
import java.text.DecimalFormat;
/**
* 功能说明: bide千分位展示
*/
@Slf4j
public class StringSerialize extends JsonSerializer<String> {
@Override
public void serialize(String str, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (StrUtil.isBlank(str)) {
jsonGenerator.writeNumber(BigDecimal.ZERO);
} else {
try {
BigDecimal bigDecimal = new BigDecimal(str);
jsonGenerator.writeString(new DecimalFormat("###,##0.00").format(bigDecimal));
} catch (Exception e) {
log.error("转换千分位异常: ", e);
}
}
}
}
对应的BigDecimal 千分位代码:
java
public class BigDecimalSerialize extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (null == bigDecimal || bigDecimal.compareTo(BigDecimal.ZERO) == 0) {
jsonGenerator.writeNumber(BigDecimal.ZERO);
} else {
jsonGenerator.writeString(new DecimalFormat("###,##0.00").format(bigDecimal));
}
}
}
效果: