【发布时间】:2015-11-22 21:54:31
【问题描述】:
我遇到了以下问题,我不知道如何解决。
我有一个基于通用界面的不同类型点的列表。 我正在使用 Java XStream 来编组和解组这些类。
public static void main(String[] args) {
List<IPoint> listOfPoint = new ArrayList<IPoint>();
listOfPoint.add(new PointTypeA(0.1));
listOfPoint.add(new PointTypeB(0.2));
listOfPoint.add(new PointTypeA(0.3));
PointSet ps = new PointSet(1, listOfPoint);
XStream xstream = new XStream(new StaxDriver());
xstream.processAnnotations(PointTypeA.class);
xstream.processAnnotations(PointTypeB.class);
xstream.processAnnotations(PointSet.class);
String xml = xstream.toXML(ps);
System.out.println(xml);
}
当我以 XML 格式打印我的对象时,我得到以下结果:
<set id="1">
<typeA>
<xCoordinate>0.1</xCoordinate>
</typeA>
<typeB>
<xCoordinate>0.2</xCoordinate>
</typeB>
<typeA>
<xCoordinate>0.3</xCoordinate>
</typeA>
</set>
但不是上面的结果,我想要以下输出:
<set id="1">
<typeA>0.1</typeA>
<typeB>0.2</typeB>
<typeA>0.3</typeA>
</set>
我想要的不是像<xCoordinate> 这样的标签,但我希望它们的值存储在类名的标签下。
我不想忽略 xCoordinate 字段的值,但我想有一个“内联值”。
有可能这样做吗?
我尝试了转换器但没有成功,我不知道如何解决这个问题。
我的课程是:
public interface IPoint {
int getSomeInformation();
}
@XStreamAlias("set")
public class PointSet {
@XStreamAsAttribute
private int id;
@XStreamImplicit
private List<IPoint> points;
public PointSet(int id, List<IPoint> points) {
super();
this.id = id;
this.points = points;
}
}
@XStreamAlias("typeA")
public class PointTypeA implements IPoint {
private double xCoordinate;
public PointTypeA(double d) {
super();
this.xCoordinate = d;
}
}
@XStreamAlias("typeB")
public class PointTypeB implements IPoint {
private double xCoordinate;
public PointTypeB(double d) {
super();
this.xCoordinate = d;
}
}
【问题讨论】:
-
我根本不知道 XStream 是如何工作的,但通常在 Java 中,您使用关键字“transient”来指示不应自动存储/检索变量。不要将它与“volatile”btw 混淆,这表明变量在缓存方面是读取和写入的。
标签: java marshalling unmarshalling xstream