【问题标题】:how to ignore fieldname while marshalling/unmarshalling java object如何在编组/解组java对象时忽略字段名
【发布时间】: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>

我想要的不是像&lt;xCoordinate&gt; 这样的标签,但我希望它们的值存储在类名的标签下。 我不想忽略 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


【解决方案1】:

您的点类转换器相当简单。

public static class CoordConverter implements Converter
{
    public boolean canConvert(Class clazz)
    {
        return PointTypeA.class == clazz;
    }

    public void marshal(Object object, HierarchicalStreamWriter hsw, MarshallingContext mc)
    {
        PointTypeA obj = (PointTypeA) object;
        hsw.setValue(String.valueOf(obj.xCoordinate));
    }

    public Object unmarshal(HierarchicalStreamReader hsr, UnmarshallingContext uc)
    {
        double val = Double.parseDouble(hsr.getValue());
        PointTypeA obj = new PointTypeA(val);
        return obj;
    }
}

你可以注册

xstream.registerConverter(new CoordConverter());

当然,此转换器对PointTypeA 类有效,但您可以轻松地将上述代码扩展为您需要的其他类和/或编写更通用的版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-27
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    相关资源
    最近更新 更多