JAXB marshalling for BigDecimal using fractionDigits

馋奶兔 提交于 2019-12-01 04:47:18
bdoughan

You will need to use XmlAdapter for this use case. Below is a sample binding file that will help you generate them. The logic would be contained in a DecimalFormatter class that contained methods for all the different required formats.

<jxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:jxb="http://java.sun.com/xml/ns/jaxb" version="2.1">
    <jxb:bindings schemaLocation="schema.xsd">
        <jxb:bindings node="//xs:element[@name='amount']">
            <jxb:property>
                <jxb:baseType>
                    <jxb:javaType name="java.math.BigDecimal"
                        parseMethod="org.example.DecimalFormatter.parseDecimal"
                        printMethod="org.example.DecimalFormatter.printDecimal_2Places" />
                </jxb:baseType>
            </jxb:property>
        </jxb:bindings>
        <jxb:bindings node="//xs:element[@name='rate']">
            <jxb:property>
                <jxb:baseType>
                    <jxb:javaType name="java.math.BigDecimal"
                        parseMethod="org.example.DecimalFormatter.parseDecimal"
                        printMethod="org.example.DecimalFormatter.printDecimal_5Places" />
                </jxb:baseType>
            </jxb:property>
        </jxb:bindings>
    </jxb:bindings>
</jxb:bindings>

For More Information

If you can change the XSD to use the precisionDecimal type documented here you might be able to use the minScale and maxScale facets set to the same value.

Rodney

I'm confused as to what could possibly be gained by maintaining the trailing zeros.

If the trailing zeros are that important to preserve, then use a string value instead of a number and use attributes to specify its width and decimals.

In any case, the trailing zeros will never impact calculations using any of these values, and the only way you would be able to present them is by converting the results into a string and padding it yourself. For some help doing that, you may want to see...

CXF client SOAP message formatting

I've created some special XmlAdapter, for example

public class BigDecimal8PlaceAdapter extends XmlAdapter<String, BigDecimal> {

@Override
public String marshal(BigDecimal v) throws Exception {
  DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
  otherSymbols.setDecimalSeparator('.');
  DecimalFormat df = new DecimalFormat("#0.00000000",otherSymbols);
  return df.format(v);
}

@Override
public BigDecimal unmarshal(String v) throws Exception {
    Double d = Double.valueOf(v);
    return BigDecimal.valueOf(d);
}

}

then i add the XmlAdapter in the properties:

@XmlElement(name = "rate", required = true)
@XmlJavaTypeAdapter(BigDecimal8PlaceAdapter.class)
protected BigDecimal rate;

Then, do the same thing with 2 decimals adapeter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!