Jackson annotation to convert BigDecimal value and set scale to 2

ern*_*oel 6 java bigdecimal jackson deserialization json-deserialization

I have POJO like where I have a BigDecimal field:

public class Foo implements Serializable {

   private BigDecimal amount;
}
Run Code Online (Sandbox Code Playgroud)

I want to have the BigDecimal value up to 2 decimal place only. Is there any annotation exist using which I can directly change it's value at the field level itself? I cannot change it's type as well.

ObjectMapper尽管它可以通过 getter在应用程序内完成。

Mic*_*ber 10

当您想要设置比例时,您需要注意舍入。您有一些选项,例如ROUND_HALF_EVEN,并且您需要决定使用哪种舍入模式。

要拦截反BigDecimal序列化,您可以编写自定义反序列化器。下面的示例展示了如何做到这一点,我们可以扩展默认值并在反序列化后设置比例:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.NumberDeserializers;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();

        Foo person = mapper.readValue(jsonFile, Foo.class);
        System.out.println(person);
    }
}

class BigDecimal2JsonDeserializer extends NumberDeserializers.BigDecimalDeserializer {

    @Override
    public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        BigDecimal value = super.deserialize(p, ctxt);

        // set scale
        value = value.setScale(2, BigDecimal.ROUND_HALF_EVEN);

        return value;
    }
}

class Foo {

    @JsonDeserialize(using = BigDecimal2JsonDeserializer.class)
    private BigDecimal amount;

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "Foo{" +
                "amount=" + amount +
                '}';
    }
}
Run Code Online (Sandbox Code Playgroud)

对于以下JSON有效负载:

{
  "amount": 16.127
}
Run Code Online (Sandbox Code Playgroud)

上面的应用程序打印:

Foo{amount=16.13}
Run Code Online (Sandbox Code Playgroud)