如何用零填充xsd:decimal?

时间:2017-07-17 08:02:00

标签: xml soap cxf

我们正在使用CXF与外部SOAP接口通话,并且有点奇怪的行为。接口要求xsd:decimal left 用零填充,最多15位。因此23将成为000000000000023

如何使用CXF实现此填充?

1 个答案:

答案 0 :(得分:0)

自己解决了。我为此创建了一个XmlJavaTypeAdapter,然后通过@XmlJavaTypeAdapter注释使用它。

public class XmlDecimalAdapter extends XmlAdapter< String, BigDecimal > 
{

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   @Override
   public String marshal( BigDecimal value ) throws Exception
   {
      final String  stringRepresentation = value.toString();

      if( value.compareTo( BigDecimal.ZERO ) < 0 ){
         String result = "-00000000000000";
         return result.substring( 0, result.length() - stringRepresentation.length() + 1 ) + stringRepresentation.substring( 1 );
      }
      String result = "000000000000000";
      return result.substring( 0, result.length() - stringRepresentation.length() ) + stringRepresentation;
   }

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   @Override
   public BigDecimal unmarshal( String value ) throws Exception
   {
      if( value.equals( "000000000000000" ) ){
         return BigDecimal.ZERO;
      }   
      if( value.startsWith( "-")  ){
         return new BigDecimal( value.replaceFirst( "^-0*", "-" ) );         
      }
      return new BigDecimal( value.replaceFirst( "^0*", "" ) );         
   }
}
相关问题