通过 XML 解析器动态将 ZonedDateTime 字符串映射到 LocalDateTime

我有一个 XML 响应字符串: <timestamp ts="2018-12-05T08:00:00+02:00">55.5</timestamp>


我在JAXB注释的帮助下将其映射为:


public class Timestamp {

    @XmlAttribute(name = "ts")

    private String timeStampAsString;

    @XmlValue

    private Double value;

它按预期工作,但我想自动解析 from DateTime,String所以我理想的解决方案应该有


public class Timestamp {


    @XmlAttribute(name = "ts")

    private LocalDateTime timeStampAsLocalDateTime;

    @XmlValue

    private Double value;

我知道我可以在以下帮助下解析字符串:


ZonedDateTime.parse(zonedDateTimeAsString).toLocalDateTime();

但我不确定是否有办法解析这个on fly。


红糖糍粑
浏览 90回答 1
1回答

牛魔王的故事

这可以通过 来完成XmlAdapter。创建一个扩展类,XmlAdapter将其转换String为LocalDateTimepublic class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public LocalDateTime unmarshal(String v) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; if (v == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return ZonedDateTime.parse(v).toLocalDateTime();&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String marshal(LocalDateTime v) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; if (v == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return v.toString();&nbsp; &nbsp; }&nbsp;}并注释要转换为 LocalDateTime 的字段:&nbsp; &nbsp; @XmlAttribute(name="ts")&nbsp; &nbsp; @XmlJavaTypeAdapter(LocalDateTimeAdapter.class)&nbsp; &nbsp; private LocalDateTime timeStampAsLocalDateTime;(正如评论中已经提到的LocalDateTime可能有问题,OffsetDateTime或者Instant可能更适合。这种方法是相同的,只是替换类和解析逻辑)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java