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.*
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.