There are many posts about creating Jackson serializers for numbers, currency, etc. For engineering applications, there is often a need to set the precision on numbers based on the units or other criteria.
For example, spatial coordinates might be constrained to 5 or 6 digits after the decimal point, and temperature might be constrained to 2 digits after the decimal point. Default serializer behavior that has too many digits or truncated exponential notation is not good. What I need is something like:
@JsonSerialize(using=MyDoubleSerializer.class, precision=6) double myValue;
and better yet be able to specify the precision at run-time. I am also using a MixIn. I could write a serializer for each class but hoped to specify on specific values.
Any ideas would be appreciated.
You may use Jackson's
ContextualSerializer
to achieve desired serialization as shown below.Firstly, create an annotation to capture precision
Next, create a contextual serializer for
Double
type which looks forPrecision
annotation on the field to be serialized and then create a new serializer for the specified precision.Finally, annotate your field to use custom serializer and set precision
Hope this helps!!
I used most of the suggested code but did the following, which uses DecimalFormat to do the formatting, which required outputting the raw text:
I am using a MixIn, so that class has:
And, finally, enable the MixIn in the ObjectMapper:
It works well to provide a precision where it applies globally on the data field.