[英]how to map java.time.Duration to XML
I have a bean with the datatype: 我有一个数据类型的bean:
private java.time.Duration duration
the class attribute is set like that: class属性设置如下:
object.setDuration(Duration.ofSeconds(2));
I want to marshall my object to xml so that duration looks like that 我想将我的对象编组为xml,以便持续时间看起来像那样
<duration>PT2S</duration>
as defined ISO 8601 如ISO 8601所定义
As far as I understand, Jaxb uses default binding data types like: 据我所知,Jaxb使用默认绑定数据类型,如:
xsd:duration javax.xml.datatype.Duration
but in my bean I don't want to include any xml dependency. 但在我的bean中,我不想包含任何xml依赖项。
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 我看到编写包装器的可能性,我可以在其中添加XmlAdapter ,但我不知道如何将java.time.Duration转换为javax.xml.datatype.Duration
I found out by searching around checking at the API's. 我通过搜索API检查发现了。 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 . 我在GitHub上找到了这个适配器的实现。 In addition to
Duration
it has the other java.time.*
types like Instant
and Period
. 除了
Duration
,还有其他java.time.*
类型,如Instant
和Period
。
The only downside is that the marshalling uses strings instead of the corresponding javax.xml.datatype.*
. 唯一的缺点是编组使用字符串而不是相应的
javax.xml.datatype.*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.