使用 Jackson 将浮点数格式化为固定点

Format a float as fixed point with Jackson

我搜索了 Jackson 文档,但找不到关于 @JsonFormatpattern 浮点数的任何好的文档。

给定一个字段

@JsonProperty("Cost")
private Double cost;

如何让 Jackson 将其格式化为具有四位精度的十进制格式 @JsonFormat 的定点数?

PS: 我知道不应该用花车换钱。请让我们讨论。

您需要为此创建自定义序列化程序。像

 @JsonProperty("amountOfMoney")
 @JsonSerialize(using = MySerializer.class)
 private Double cost;

 public class MySerializerextends JsonSerializer<Double> {
    @Override
    public void serialize(Double value, JsonGenerator generator, SerializerProvider provider) throws IOException,
            JsonProcessingException {  
        double roundedValue = value*10000;
        roundedValue = Math.round(roundedValue );
        roundedValue = roundedValue /10000;          
        generator.writeNumber(roundedValue );
    }
 }

您可以在此处查看 class https://fasterxml.github.io/jackson-databind/javadoc/2.3.0/com/fasterxml/jackson/databind/JsonSerializer.html

四舍五入的部分可能不是最好的。您可以随心所欲地进行;) 使用十进制格式也可以。如果您使用 writeNumber,它将在结果 Json 中将值打印为数字。这就是为什么我将我的答案从 writeString 更改为使用十进制格式。

如果实现允许的话,你应该可以使用@Json格式的模式。

Datatype-specific additional piece of configuration that may be used to further refine formatting aspects. This may, for example, determine low-level format String used for Date serialization; however, exact use is determined by specific JsonSerializer

但是我相信对于 jackson 来说它只适用于日期。

基于我正在使用的@Veselin 的回答

public class DoubleDecimalSerializerWithSixDigitPrecisionAndDotSeparator
    extends JsonSerializer<Double> {

  @Override
  public void serialize(Double value, JsonGenerator generator, SerializerProvider serializers)
      throws IOException {
    generator.writeNumber(String.format(Locale.US, "%.6f", value));
  }
}

用例是在德国生成 CSV,所以我不关心 JSON 格式,想要一个“.”作为小数分隔符。

您可以在自定义序列化程序中指定您自己的格式化程序class。

    formatter = new DecimalFormat();
    formatter.setMaximumFractionDigits(2);
    formatter.setMinimumFractionDigits(2);
    formatter.setGroupingUsed(false);
    DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance();
    sym.setDecimalSeparator('.');
    formatter.setDecimalFormatSymbols(sym);

然后,在实际序列化方法中:

    final String output = formatter.format(value);
    jsonGenerator.writeNumber(output);