I have a bean with the datatype:
private java.time.Duration duration
the class attribute is set like that:
object.setDuration(Duration.ofSeconds(2));
I want to marshall my object to xml so that duration looks like that
<duration>PT2S</duration>
as defined ISO 8601
As far as I understand, Jaxb uses default binding data types like:
xsd:duration javax.xml.datatype.Duration
but in my bean I don't want to include any xml dependency.
I see the possibility of writing a wrapper where I can add a XmlAdapter, but I don't know how to transform java.time.Duration to javax.xml.datatype.Duration
I found out by searching around checking at the API's. Here is my code:
import java.time.Duration
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.datatype.DatatypeFactory;
public class DurationAdapter extends XmlAdapter<javax.xml.datatype.Duration, Duration>
{
@Override
public Duration unmarshal(javax.xml.datatype.Duration v) throws Exception {
return Duration.parse(v.toString());
}
@Override
public javax.xml.datatype.Duration marshal(Duration v) throws Exception {
return DatatypeFactory.newInstance().newDuration(v.toString());
}
}
I found an implementation of this adapters on GitHub. In addition to Duration
it has the other java.time.*
types like Instant
and Period
.
The only downside is that the marshalling uses strings instead of the corresponding javax.xml.datatype.*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With