简体   繁体   English

Spring MVC Jaxb2Marshaller无法正确处理继承类

[英]Spring MVC Jaxb2Marshaller does not handle inheritance class properly

I have a Spring MVC controller to generate XML, it generates regular objects without any problem. 我有一个Spring MVC控制器来生成XML,它可以正常生成对象。 However, looks like it does not support polymorphism properly. 但是,它似乎不正确地支持多态。 I guess it might be configuration issue. 我想这可能是配置问题。

Here is my class hierarchy. 这是我的班级层次结构。

abstract class Base {
   String attr1;
}

class Child1 {
   String attrChild1;
}

class Child2 {
   String attrChild2;
}

@XmlRootElement
class MyList {

   @XmlElement (name="list")
   List<Base> lists;
}

Then I add 1 instance of Child1 and one instance of Child2 into lists. 然后,将1个Child1实例和1个Child2实例添加到列表中。

If I manually use JAXB to marshall it, it will generate some XML like this 如果我手动使用JAXB来编组它,它将生成一些这样的XML

<list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="child1">
  <attr1>...</attr1>
  <attrChild1>...</attrChild1>
</list>
<list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="child2">
  <attr1>...</attr1>
  <attrChild2>...</attrChild2>
</list>

However, if I go through spring, I will only get 但是,如果我经历春天,我只会

<list>
  <attr1>...</attr1>
</list>
<list>
  <attr1>...</attr1>
</list>

Any suggestions? 有什么建议么?

Here is my controller class 这是我的控制器课

@RequestMapping(value="/rest/test", method=RequestMethod.GET, produces="application/xml")
public @ResponseBody MyList getMyList() {
      MyList myList = ....;
      // add instance of Child1/2
      return myList;
}

Try adding: 尝试添加:

@XmlSeeAlso({Child1.class, Child2.class})
abstract class Base {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM