BigDecimal has scientific notation in soapy posts

I have a strange problem with our web service. I have an OrderPosition object that has a price (which is xsd: decimal with fractionDigits = 9). Apache CXF generates proxy classes for me, and this is a BigDecimal field. When I want to send a value greater than 10000000.00000, this field in the soap message has scientific notation (for example, 1.1423E + 7).

How can I guarantee that this value has not been sent in scientific notation.

+6
source share
2 answers

Here is one way to do it.

BigDecimal has a constructor that takes an input number as a string. This, when used, preserves input formatting when the .toString() method is called. eg

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

will print 10000000.00000 .

This can be used in Jaxb XmlAdapters . Jaxb XmlAdapters offer a convenient way to manage / customize the process of sorting / deleting files . A typical adapter for BigDecimmal will look like this.

 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 in the Jaxb context. Here is a link with a complete example.

+3
source

@ Santosh Thank you! The XMLAdapter was what I needed. Also, as I said in my question, I generate client classes with Apache CXF. In this form, I had to add the following code to bindings.xjb (the binding file that is used for cxf-codegen-plugin in maven).

 <jaxb:javaType name="java.math.BigDecimal" xmlType="xs:decimal" parseMethod="sample.BigDecimalFormater.parseBigDecimal" printMethod="sample.BigDecimalFormater.printBigDecimal" /> 

This is my formatting code:

 public class BigDecimalFormater { public static String printBigDecimal(BigDecimal value) { value.setScale(5); return value.toPlainString(); } public static BigDecimal parseBigDecimal(String value) { return new BigDecimal(value); } } 

Then this plugin generates Adapter for me

 public class Adapter1 extends XmlAdapter<String, BigDecimal> { public BigDecimal unmarshal(String value) { return (sample.BigDecimalFormater.parseBigDecimal(value)); } public String marshal(BigDecimal value) { return (sample.BigDecimalFormater.printBigDecimal(value)); } } 

In the generated BigDecimal class, the field has the annotation @XmlJavaTypeAdapter (Adapter1.class) and fixes the problem.

0
source

Source: https://habr.com/ru/post/958542/


All Articles