Java to Jackson JSON serialization: Money fields

后端 未结 7 1438
臣服心动
臣服心动 2020-12-04 12:24

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

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 12:34

    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 {
        @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));
        }
    }
    

提交回复
热议问题