jaxb 继承

现有要求,希望得到如下的数据

<root>
   <auth>
     <user></user>
     <token></token>
   <auth>

  <data>
       主要的问题在这里,这里标签,要根据上下文而发生变化。
  </data>
</root>

于是我想到了,是否可以用过用继承来解决data标签的问题呢?不知道,以前没写过,那就试试吧。还好,最终终于是实现了。代码如下

先是root类的代码

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

	@XmlElement(name = "auth")
	private Auth auth;

        // 重点看这里
        @XmlElementRef
	private Data data;

       // getter and setter
}

再是Auth类

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

@XmlAccessorType(XmlAccessType.FIELD)
public class Auth {
 
	@XmlElement(name = "user")
	private String user;

	@XmlElement(name = "token")
	private String token;
        
       // getter and setter
}

好了,以上比较简单,重点来了,先看Data类,是怎么变化的吧

import javax.xml.bind.annotation.XmlSeeAlso;

@XmlSeeAlso(value = { org.test.OrderData.class, org.test.UserData.class })
public class Data {
}

 看到了吧,父类里, XmlSeeAlso,写上它有哪些子类,差不多是这个意思吧。

再来一个OrderData

@XmlRootElement(name = "XML_DATA")
@XmlAccessorType(XmlAccessType.FIELD)
public class OrderData extends org.test.Data {
}

 你没有看错,OrderData里,写了个XmlRootElement标签。

好了,以上就是继承的实现了。主要是用到了@XmlSeeAlso,@XmlElementRef这两个标签。

XmlSeeAlso,主要是用来说明,父类有哪些个子类。

XmlElementRef,它的作用是:如果不你写的话,生成的XML,会存在xsi:样子的东东,也就是所谓的命名空间吧。自己尝试去吧。

参考文章:

这篇文章,使我确信,可以通过继承的方式来解决

http://blog.csdn.net/u014021905/article/details/42215137

这个里面提到了怎么实现继承,于是@XmlSeeAlso进入了我的视线。

http://blog.csdn.net/xiaofanku/article/details/49977097

这是怎么样去掉命名空间

http://blog.csdn.net/inaoen/article/details/49908875

这是为什么要在子类上写上@XmlRootElement标签。曾经我出现过个么个错误 @XmlElementRef 无效: 或其任意子类对此上下文是未知的。

http://www.apihome.cn/api/java/XmlElementRef.html

 打个小广告

我建立了个群  622539266  JAVA知识交流,有在学JAVA的,或是想学JAVA的,可以加进来哦。

猜你喜欢

转载自hnzmdpan.iteye.com/blog/2376276