在JAXB,如何使用@XmlJavaTypeAdapters注解? [英] In JAXB, how to use @XmlJavaTypeAdapters annotation?

查看:4146
本文介绍了在JAXB,如何使用@XmlJavaTypeAdapters注解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改变从XML解组到Java类JAXB的时候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.

但我不把@XmlJavaTypeAdapter任何注释Java类。

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

请给我的例子使用它。

推荐答案

作为一个有趣的不谈,你实际上并不需要XMLGregorianCalendar的适应时间,因为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!

这篇关于在JAXB,如何使用@XmlJavaTypeAdapters注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆