rocotocloc
rocotocloc

Reputation: 477

MOXy JAXB: how to use BigDecimalAdapter with different precisions

I have a BigDecimalAdapter to format all BigDecimal types of my model. The declaration in the package-info file is:

@XmlJavaTypeAdapters({@XmlJavaTypeAdapter(value=BigDecimalAdapter.class,type=BigDecimal.class)})

My problem is that I must format several BigDecimal with different precissions.

For example, I have two objects:

public class Invoice {

    @XmlPath("InvoiceTotals/InvoiceTotal/text()")
    private BigDecimal invoiceTotal;
}

and

public class Discount {

    @XmlPath("DiscountAmount/text()")
    private BigDecimal discountAmount;

}

Now, if the values are:

invoice.invoiceTotal = 10.000000000;
discount.discountAmount = 25.00000000;

how can I get next results in the final XML?

<invoiceTotal>10.00<invoiceTotal/>
<discountAmount>25.0000<discountAmount/>

I mean, 2 decimals in the first case and 4 decimals in the second.

Thank you very much.

Upvotes: 1

Views: 275

Answers (1)

bdoughan
bdoughan

Reputation: 149017

You will need to introduce an XmlAdapter for each of the representations of BigDecimal. Then instead of registering the XmlAdapter at the package level you will need to register them at the property level. Below is an example.

Invoice

public class Invoice {

    @XmlPath("InvoiceTotals/InvoiceTotal/text()")
    @XmlJavaTypeAdapter(value=BigDecimalTwoPlacesAdapter.class)
    private BigDecimal invoiceTotal;
}

Discount

public class Discount {

    @XmlPath("DiscountAmount/text()")
    @XmlJavaTypeAdapter(value=BigDecimalFourPlacesAdapter.class)
    private BigDecimal discountAmount;

}

Upvotes: 1

Related Questions