Java to Jackson JSON serialization: Money fields

后端 未结 7 1410
臣服心动
臣服心动 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:50

    You can use a custom serializer at your money field. Here's an example with a MoneyBean. The field amount gets annotated with @JsonSerialize(using=...).

    public class MoneyBean {
        //...
    
        @JsonProperty("amountOfMoney")
        @JsonSerialize(using = MoneySerializer.class)
        private BigDecimal amount;
    
        //getters/setters...
    }
    
    public class MoneySerializer extends JsonSerializer<BigDecimal> {
        @Override
        public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
                JsonProcessingException {
            // put your desired money style here
            jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
    }
    

    That's it. A BigDecimal is now printed in the right way. I used a simple testcase to show it:

    @Test
    public void jsonSerializationTest() throws Exception {
         MoneyBean m = new MoneyBean();
         m.setAmount(new BigDecimal("20.3"));
    
         ObjectMapper mapper = new ObjectMapper();
         assertEquals("{\"amountOfMoney\":\"20.30\"}", mapper.writeValueAsString(m));
    }
    
    0 讨论(0)
提交回复
热议问题