在 JAXB 中,如何使用 @XmlJavaTypeAdapters 注解?

2022-01-13 00:00:00 xml annotations package java jaxb

从xml解组到JAXB的Java类时,我想将javax.xml.datatype.XMLGregorianCalendar"更改为java.util.Date".

I want to change "javax.xml.datatype.XMLGregorianCalendar" to "java.util.Date" when unmarshalling from xml to Java class of JAXB.

但我没有在 Java 类中添加任何 @XmlJavaTypeAdapter 的注解.

But I don't put any annotations of @XmlJavaTypeAdapter in Java classes.

所以,我打算尝试使用@XmlJavaTypeAdapters的注解,但是不知道怎么用……

So, I'm going to try to use an annotation of @XmlJavaTypeAdapters, but I don't know how to use it...

请给我展示使用它的例子.

Please show me examples for using it.

推荐答案

顺便说一句,您实际上不需要将 XMLGregorianCalendar 适配到 Date,因为 JAXB 本身就支持 java.util.Date —— 像这样:

As an interesting aside, you don't actually need to adapt XMLGregorianCalendar to Date, since JAXB supports java.util.Date natively -- like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Example {
    @XmlSchemaType(name = "date")
    public Date publishingDate;
}

如果你需要它,@XmlJavaTypeAdapter 可以像这样工作,假设你的自定义类:

If you need it, @XmlJavaTypeAdapter can work like this, assuming your custom class:

public class SillyDate {
    public SillyDate(int year, int month, int day) {
        super();
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public String toString() {
      return "SillyDate [year=" + year + ", month=" + month + ", day=" + day + "]";
    }

    public int year;
    public int month;
    public int day;
}

您需要一个 JAXB 可以理解的类,然后在该类和自定义类之间编写一个适配器,如下所示:

You need a class which JAXB can understand, and then write an adapter between that class and the custom class, like this:

public class SillyDateAdapter extends XmlAdapter<XMLGregorianCalendar, SillyDate> {
    public SillyDate unmarshal(XMLGregorianCalendar val) throws Exception {
      return new SillyDate(val.getYear(), val.getMonth(), val.getDay());
    }

    public XMLGregorianCalendar marshal(SillyDate val) throws Exception {
      return DatatypeFactory.newInstance().newXMLGregorianCalendarDate(val.year, val.month, val.day, 0);
    }
}

现在您可以在自己的类中使用它,如下所示:

Now you can use that in your own classes, like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Example2 {
    @XmlSchemaType(name = "date")
    @XmlJavaTypeAdapter(type=XMLGregorianCalendar.class,value =SillyDateAdapter.class)
    public SillyDate publishingDate;
}

网上有很多使用@XmlJavaTypeAdapter 的好例子,比如这个 和 这个一个,还有其他几个.适应愉快!

There are plenty of good examples of using the @XmlJavaTypeAdapter available on the net, like this one and this one, and several others. Happy adapting!

相关文章