When REST API is consumed by JavaScript, in order to prevent the loss of precision, BigDecimal is normally passed as a string. While adding a custom serializer is easy, I think this is a very common case and warrants an out of the box SerializationFeature.
This is bit too granular thing, at this point, as I would hope to avoid adding new non-general SerializationFeatures. But there is @JsonFormat already, with shape property (Shape.STRING) that should work.
It may be used on specific properties, but also via "configOverrides" for type; something like
mapper.configOverrides(BigDecimal.class).
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
If this does not yet work (it requires support from serializer), it should be added.
I'll leave this open for verification if anyone has time.
That seems reasonable enough. I'll test on monday and come back.
@cen1 Thanks. And thank you for reporting this; I agree that this is important use case for javascript clients.
Ok while conversion does work for primitive types, it is not yet supported for BigInteger or BigDecimal. Needs to be added.
@cowtowncoder I cannot see anywhere what method is called on the BigDecimal to convert it to a string? Is it toPlainString(), toString() or toEngineeringString()?
@hashhar what are you trying to achieve, specifically? Method will be either injackson-core (at low-level JsonGenerator implementation), or within jackson-databind. In latter case, it'd be in BigDecimalAsStringSerializer defined as inner class of NumberSerializer.
I want to control how the BigDecimal gets converted into a string when using the JsonFormat.Shape support. For some BigDecimals I might want to use toPlainString() (think while dumping into a CSV) while for some I might be okay with toString()/toEngineeringString().
I found the code and it looks like we even have a config for it as StreamWriteFeature.WRITE_BIGDECIMAL_AS_PLAIN.
For other people who come across this, see the code at https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ser/std/NumberSerializer.java#L127
Ok. Yes, at some point it may make sense to write a custom serializer: with createContextual() you have access to configuration and annotation information, including format settings.
Most helpful comment
This is bit too granular thing, at this point, as I would hope to avoid adding new non-general
SerializationFeatures. But there is@JsonFormatalready, withshapeproperty (Shape.STRING) that should work.It may be used on specific properties, but also via "configOverrides" for type; something like
If this does not yet work (it requires support from serializer), it should be added.
I'll leave this open for verification if anyone has time.