Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to map java.time.Duration to XML

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

like image 929
Oscar Castiblanco Avatar asked Dec 05 '14 10:12

Oscar Castiblanco


2 Answers

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());
    }
}
like image 84
Oscar Castiblanco Avatar answered Sep 28 '22 03:09

Oscar Castiblanco


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.*.

like image 32
jgibson Avatar answered Sep 28 '22 03:09

jgibson