Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BigDecimal in JAXB marshalling

I have a REST webservice with JAXB fields annotations. For example,

@XmlAccessorType(XmlAccessType.PROPERTY)
public class MyClass{
  private BigDecimal sum;
  //+ getter and setter
}

If field "sum" contains big value, for example, 1234567890.12345, it marshalls to 1.23456789012345E9 How to write a rule for marshalling only this class?

like image 635
Mikhail Kopylov Avatar asked Dec 17 '12 08:12

Mikhail Kopylov


2 Answers

Create adaptor

puclic class BigDecimalAdaptor implements XmlAdapter<String, BigDecimal>

and use for (XmlAccessType.FIELD) access

@XmlJavaTypeAdapter(BigDecimalAdaptor.class)
private BigDecimal sum;   

and for (XmlAccessType.PROPERTY) access

@XmlJavaTypeAdapter(BigDecimalAdaptor.class)  
public getSum()
{
   return sum;
}

adaptor can be like

public class BigDecimalAdapter extends XmlAdapter<String, BigDecimal>{

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

    @Override
    public BigDecimal unmarshal(String s) throws Exception 
    {
       return new BigDecimal(s);
    }
}
like image 100
Ilya Avatar answered Oct 05 '22 12:10

Ilya


You write an XmlAdapter<String, BigDecimal> and you annotate the getter of sum with it: @XmlJavaTypeAdapter(BigDecimalStringAdapter.class).

like image 22
steffen Avatar answered Oct 05 '22 11:10

steffen