acorello
acorello

Reputation: 4653

How to tell jaxb to truncate a BigDecimal when marshalling to xml?

I have these two classes:

@XmlAccessorType(XmlAccessType.FIELD)
public class OpportunityLocation
{

    @XmlElement
    private LatitudeLongitude coordinates;
    [...]
}

public class LatitudeLongitude implements Serializable
{
    private BigDecimal latitude;
    private BigDecimal longitude;
    [...]
}

when OpportunityLocation is serialized I get

<location>
    [...]
    <coordinates>
    <latitude>51.53684899999999657893567928113043308258056640625</latitude>
    <longitude>-0.1325880000000000114024345521102077327668666839599609375</longitude>
    </coordinates>

Now I've been asked to provide an xsd to validate the xml, I set the type of latitude and longitude to xsd:decimal but the validator complains that

 Element 'latitude': '51.53684899999999657893567928113043308258056640625' is not a valid value of the atomic type 'xs:decimal'.

(same for longitude)

The xsd fragment describing the coordinates is

<xs:complexType name="latitudeLongitude">
    <xs:all>
        <xs:element name="latitude" type="xs:decimal"/>
        <xs:element name="longitude" type="xs:decimal"/>
    </xs:all>
</xs:complexType>

I think the best solution would be to truncate the lat/long values, as there is no point to have that much precision in the first place.

How do I instruct JAXB to do that?

Upvotes: 3

Views: 3604

Answers (2)

Vincenzo Z
Vincenzo Z

Reputation: 133

Or simply use BigDecimal.setScale(). No need for an XmlAdapter if applicable to your case.

BigDecimal bd = new BigDecimal((double) 1.2345);
bd = bd.setScale(2, RoundingMode.HALF_UP);

Upvotes: 2

bdoughan
bdoughan

Reputation: 149017

You can do this using an XmlAdapter. Below is a similar example demonstrating the concept with the Joda-Time classes:

Upvotes: 1

Related Questions