Currently, I\'m using Jackson to send out JSON results from my Spring-based web application.
The problem I\'m having is trying to get all money fields to output with
You can use @JsonFormat
annotation with shape
as STRING
on your BigDecimal
variables. Refer below:
import com.fasterxml.jackson.annotation.JsonFormat;
class YourObjectClass {
@JsonFormat(shape=JsonFormat.Shape.STRING)
private BigDecimal yourVariable;
}
Inspired by Steve, and as the updates for Java 11. Here's how we did the BigDecimal reformatting to avoid scientific notation.
public class PriceSerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
// Using writNumber and removing toString make sure the output is number but not String.
jgen.writeNumber(value.setScale(2, RoundingMode.HALF_UP));
}
}
I had the same issue and i had it formatted into JSON as a String instead. Might be a bit of a hack but it's easy to implement.
private BigDecimal myValue = new BigDecimal("25.50");
...
public String getMyValue() {
return myValue.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
}
As Sahil Chhabra suggested you can use @JsonFormat
with proper shape
on your variable.
In case you would like to apply it on every BigDecimal
field you have in your Dto's
you can override default format for given class.
@Configuration
public class JacksonObjectMapperConfiguration {
@Autowired
public void customize(ObjectMapper objectMapper) {
objectMapper
.configOverride(BigDecimal.class).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
}
}
Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:
SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);
In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).
I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.