Reputation: 3236
I have a requirement to leave 1 decimal place on numbers returned from a Spring-boot application using Jackson.
For example, a double with the value 9
should be returned as 9.0
and the value 9.5
should be returned as 9.5
.
These should fit into the json type 'number', not 'string' (They do not have quotation marks around them, so not "9.0"
, but instead I'm after 9.0
.
I have tried writing a custom serialiser using JsonGenerator's writeRaw(String) and writeRawValue, as well as various writeNumber methods.
The writeRawValue suggests it will write the value:
without any modifications, but assuming it must constitute a single legal JSON value (number, string, boolean, null, Array or List)
However it is removing the .0
, or at least that .0
is gone by the time it makes it's way out of spring boot. There is nothing that I can see in the Json spec which suggests trimming trailing 0's is required, and there is actually an example with -122.026020
in the spec itself.
How can I get the .0
to show up in my responses? Here is what i've tried:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
public class MyCustomSerialiser extends JsonSerializer<Double> {
@Override
public void serialize(Double value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeRawValue("123.450");
}
}
Upvotes: 0
Views: 4336
Reputation: 285
It seems not the case if you are using jackson version 2.8.8. Also ensure you are looking at row out put of json. as json viewer some time format and remove trailing zeros.
Upvotes: 0
Reputation: 1658
in your custom serializer, just create a bigdecimal from your double, and specify the precision you want. Then just call writeNumber in the jsonGenerator.
Edit: Depending on the client being used to test results, 0s may be automatically removed from the "view". OP found that it was Postman (tool he was using to check results) the one removing 0s when displaying content, but the json he was generating was ok.
Upvotes: 5