[英]GSON serialization issue in Java for BigDecimal
Need to convert JSON string into Java object.需要将JSON字符串转换成Java object。
{
"amount":1.0000
}
I am trying to covert string using GSON.fromjson(response, Amount.class);我正在尝试使用 GSON.fromjson(response, Amount.class); 来隐藏字符串
This value was changed to 1.0 in object. Please help to resolve this.这个值在object改成了1.0,请帮忙解决。
I tried the same thing in objectmapper also.我也在 objectmapper 中尝试了同样的事情。 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:然后在您的 POJO 中将注释放在您的"amount"
字段中:
@JsonSerialize(using = SerializerBigDecimal.class)
private BigDecimal amount;
Considering your Amount class is like this:考虑到您的金额 class 是这样的:
class Amount {
private BigDecimal amount;
public BigDecimal getAmount() {
return amount;
}
}
ObjectMapper parsed it correctly. ObjectMapper 正确解析了它。
@Test
void amountPrecisionTest() throws IOException {
Amount amount = new ObjectMapper().readValue("{\"amount\":1.0000}", Amount.class);
assertEquals(BigDecimal.valueOf(1.0000).setScale(4), amount.getAmount());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.