Java to Jackson JSON序列化:Money字段 [英] Java to Jackson JSON serialization: Money fields

查看:443
本文介绍了Java to Jackson JSON序列化:Money字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在使用Jackson从我的基于Spring的Web应用程序发送JSON结果。



我遇到的问题是试图获得所有资金要输出2个小数位的字段。我无法使用 setScale(2)解决此问题,因为25.50之类的数字被截断为25.5等



<有没有其他人处理过这个问题?我正在考虑使用自定义的Jackson序列化程序创建Money类...您可以为字段变量创建自定义序列化程序吗?你可能......但即使如此,我怎么能让我的客户序列化器将数字添加为2位小数?

解决方案

您可以在货币领域使用自定义序列化程序。这是MoneyBean的一个例子。字段金额使用 @JsonSerialize(使用= ...)进行注释。

 公共类MoneyBean {
// ...

@JsonProperty(amountOfMoney)
@JsonSerialize(using = MoneySerializer.class)
private BigDecimal数量;

// getters / setters ...
}

公共类MoneySerializer扩展JsonSerializer< BigDecimal> {
@Override
public void serialize(BigDecimal value,JsonGenerator jgen,SerializerProvider provider)抛出IOException,
JsonProcessingException {
//把你想要的钱款放在这里
jgen .writeString(value.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
}
}

就是这样。现在以正确的方式打印BigDecimal。我使用一个简单的测试用例来显示它:

  @Test 
public void jsonSerializationTest()抛出异常{
MoneyBean m = new MoneyBean();
m.setAmount(new BigDecimal(20.3));

ObjectMapper mapper = new ObjectMapper();
assertEquals({\amountOfMoney \:\20.30 \},mapper.writeValueAsString(m));
}


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 2 decimal places. I wasn't able to solve this problem using setScale(2), as numbers like 25.50 are truncated to 25.5 etc

Has anyone else dealt with this problem? I was thinking about making a Money class with a custom Jackson serializer... can you make a custom serializer for a field variable? You probably can... But even still, how could I get my customer serializer to add the number as a number with 2 decimal places?

解决方案

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

这篇关于Java to Jackson JSON序列化:Money字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆