开发者

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开发者_如何学Go 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?


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);


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

  • http://blog.bdoughan.com/2011/05/jaxb-and-joda-time-dates-and-times.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜