java返回json设置自定义的格式

时间:2020-12-29 22:15:18
  • 使用注解@JsonSerialize(using = CustomPriceSerialize.class)

  • 创建自定义的格式化类(可为内部类)


    /**
    * 设置默认返回的小数类型(0.01 元)
    */
    class CustomPriceSerialize extends JsonSerializer<BigDecimal> {
    private DecimalFormat df = new DecimalFormat("#0.00"); public CustomPriceSerialize() {
    } public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeString(this.df.format(value));
    }
    }