在肥皂消息中有科学记数法

在肥皂消息中有科学记数法

本文介绍了BigDecimal 在肥皂消息中有科学记数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网络服务遇到了奇怪的问题.我有一个对象 OrderPosition,它有一个价格(它是 xsd:decimal,fractionDigits = 9).Apache CXF 为我生成代理类,这个字段是 BigDecimal.当我想发送大于 10000000.00000 的值时,soap 消息中的这个字段有科学计数法(例如 1.1423E+7).

如何强制该值未以科学计数法发送.

解决方案

这是一种可以做到的方法.

BigDecimal 有一个将输入数字作为字符串的构造函数.使用时,它会在调用其 .toString() 方法时保留输入格式.例如

BigDecimal bd = new BigDecimal("10000000.00000");System.out.println(bd);

将打印10000000.00000.

这可以在 Jaxb XmlAdapters 中使用.Jaxb XmlAdapter 提供了一种方便的方式来控制/自定义编组/解组过程.BigDecimmal 的典型适配器如下所示.

public class BigDecimalXmlAdapter extends XmlAdapter{@覆盖公共字符串元帅(BigDecimal bigDecimal)抛出异常{if (bigDecimal != null){返回 bigDecimal.toString();}别的 {返回空;}}@覆盖public BigDecimal unmarshal(String s) 抛出异常 {尝试 {返回新的 BigDecimal(s);} catch (NumberFormatException e) {返回空;}}}

这需要在 Jaxb 上下文中注册.这里是完整示例的链接.

I have got strange problem with our webservice.I have got object OrderPosition which has got a price (which is xsd:decimal with fractionDigits = 9). Apache CXF generate proxy classes for me, and this field is BigDecimal. When I'd like to send value greater than 10000000.00000, this field in soap message has got scientific notation (for example 1.1423E+7).

How can I enforce that the value has not been sent in scientific notation.

解决方案

Here is one way this can be done.

BigDecimal has a constructor which takes input number as a string. This when used, preservs the input formatting when its .toString() method is called. e.g.

will print 10000000.00000.

This can be leveraged in Jaxb XmlAdapters. Jaxb XmlAdapters offer a convenient way to control/customize the marshalling/unmashalling process. A typical adapter for BigDecimmal would look like as follows.

public class BigDecimalXmlAdapter extends XmlAdapter{

    @Override
    public String marshal(BigDecimal bigDecimal) throws Exception {
        if (bigDecimal != null){
            return bigDecimal.toString();
        }
        else {
            return null;
        }
    }

    @Override
    public BigDecimal unmarshal(String s) throws Exception {
        try {
            return new BigDecimal(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}

This needs to be registered with Jaxb context. Here is the link with complete example.

这篇关于BigDecimal 在肥皂消息中有科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 23:37