Using BigDecimal in JAXB marshalling

前端 未结 2 887
栀梦
栀梦 2021-02-19 23:28

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

@XmlAccessorType(XmlAccessType.PROPERTY)
public class MyClass{
  private BigDecimal sum;
  /         


        
相关标签:
2条回答
  • 2021-02-19 23:31

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

    0 讨论(0)
  • 2021-02-19 23:52

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题