How to map java.time.Duration to XML

I have a bean with a data type:

private java.time.Duration duration 

the class attribute is set as follows:

 object.setDuration(Duration.ofSeconds(2)); 

I want to arrange my object in xml so that the duration looks like

 <duration>PT2S</duration> 

as defined by ISO 8601

As far as I understand, Jaxb uses default binding data types , for example:

 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 an XmlAdapter , but I don't know how to convert java. time.Duration to javax.xml.datatype.Duration

+5
source share
2 answers

I found out by checking the API check. 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()); } } 
+6
source

I found an implementation of these adapters on GitHub . In addition to Duration it has other types of java.time.* , Such as Instant and Period .

The only drawback is that marshalling uses strings instead of the corresponding javax.xml.datatype.* .

+1
source

Source: https://habr.com/ru/post/1208417/


All Articles