简体   繁体   中英

GSON serialization issue in Java for BigDecimal

Need to convert JSON string into Java object.

{
  "amount":1.0000
}

I am trying to covert string using GSON.fromjson(response, Amount.class);

This value was changed to 1.0 in object. Please help to resolve this.

I tried the same thing in objectmapper also. It is not working

You should write custom seriliazer, something like this:

 public class SerializerBigDecimal extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if(Objects.isNull(value)) {
            gen.writeNull();
        } else {
                         // take the floor value
            gen.writeNumber(value.setScale(4, RoundingMode.FLOOR));
        }
    }
}

And then in your POJO put annotation on your "amount" field:

@JsonSerialize(using = SerializerBigDecimal.class)
private BigDecimal amount;

Considering your Amount class is like this:

class Amount {
    private BigDecimal amount;

    public BigDecimal getAmount() {
        return amount;
    }
}

ObjectMapper parsed it correctly.

@Test
void amountPrecisionTest() throws IOException {
    Amount amount = new ObjectMapper().readValue("{\"amount\":1.0000}", Amount.class);

    assertEquals(BigDecimal.valueOf(1.0000).setScale(4), amount.getAmount());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM