【问题标题】:XStream collection of type ad subtypeXStream 集合类型广告子类型
【发布时间】:2014-03-26 08:29:43
【问题描述】:

我有这样的课程:

class A{
//pojo
}
class B extends {
// pojo
}
class C{
@XStreamImplicit( itemFieldName="A")
private ArrayList<A> aList = null;
}

提交的C类aList包含一种对象类型A.class和一种类型B.class。

我可以将类序列化和反序列化到这个xml:

<c>
 <aList>
  <a/>
  <a/>
 </aList>
</c> 

但我希望 xml 文件看起来像这样:

<c>
 <aList>
  <a/>
  <b/>
 </aList>
</c> 

有可能吗?我该怎么做?

【问题讨论】:

    标签: java xml xstream


    【解决方案1】:

    这对我有用:

    @XStreamAlias("a")
    public class A {
    
    }
    
    @XStreamAlias("b")
    public class B extends A {
    
    }
    
    @XStreamAlias("c")
    public class C {
        private ArrayList<A> aList = null;
    
        public C() {
            aList = new ArrayList<A>();
            aList.add(new A());
            aList.add(new B());
            aList.add(new A());
        }
    
        public static void main(String[] args) {
            C c = new C();
    
            XStream x = new XStream();
            x.processAnnotations(A.class);
            x.processAnnotations(B.class);
            x.processAnnotations(C.class);
    
            System.out.println(x.toXML(c));
        }
    
    }
    

    并产生:

    <c>
      <aList>
        <a/>
        <b/>
        <a/>
      </aList>
    </c>
    

    如果您不想为每个可能的类调用 processAnnotations,您可以使用反射 API 编写一些动态代码并循环处理所有类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      相关资源
      最近更新 更多