I have a JSON
seriliazer which serializes a BigDecimal
in the way presented in this SO answer:
public class MoneySerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(bigDecimal.toPlainString());
}
}
It is used in my POJO
:
public class MoneyBean {
//...
@JsonSerialize(using = MoneySerializer.class)
private BigDecimal amount1;
@JsonSerialize(using = MoneySerializer.class)
private BigDecimal amount2;
// getters/setters
}
Requirements:
- I have to remove all trailing zeros but keep two from amount1 eg: if result is 100.0000 - intended result is 100.00
- For amount2 I have to remove all trailing zeros eg: if result is 100.0000 - intended result is 100
Is there any way the MoneySerializer
can be adjusted to pass another argument as minimumScale
so that it can remove automatically? Obviously this logic can be moved to service or we can create different serializer for each case but here I am looking for a single annotation which solves the problem something like :
@MyJsonSerialize(using = MoneySerializer.class, minimumScale = 2)
private BigDecimal amount1; //100.00000 -> 100.00
@MyJsonSerialize(using = MoneySerializer.class, minimumScale = 0)
private BigDecimal amount2; //100.00000 -> 100
@MyJsonSerialize(using = MoneySerializer.class, minimumScale = 4)
private BigDecimal amount3; //100.00000 -> 100.0000
Tried with different serializer or moving trailing zeros removal logic to service class and that is working but looking for a configurable annotation based solution.