List根元素的XStream别名 [英] XStream Alias of List root elements

查看:152
本文介绍了List根元素的XStream别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够根据列表中包含的对象类型对根列表元素进行别名。例如,这是我当前的输出:

I want to be able to alias the root list element depending upon what type of objects are contained in the list. For example, this is my current output:

<list>
<coin>Gold</coin>
<coin>Silver</coin>
<coin>Bronze</coin>
</list>

这就是我想要的样子:

<coins>
<coin>Gold</coin>
<coin>Silver</coin>
<coin>Bronze</coin>
</coins>

我可以在全球范围内通过说所有列表应该别名为硬币来做到这一点,但我有很多不同的列表,这将无法正常工作。关于如何做到这一点的任何想法?看起来它应该很简单,但当然不是。

I can do this at a global level by saying all lists should be aliased to coins, but I have a lot of different lists and this won't work. Any ideas on how to do this? Seems like it should be simple, but of course, it isn't.

编辑:我应该指定,我正在尝试将对象序列化为xml。我使用Spring 3 MVC作为我的Web框架。

I should specify, I am trying to serialize objects to xml. I am using Spring 3 MVC as my web framework.

推荐答案

假设你有一个带有type属性的Coin类,如下所示:

Let's say you have a Coin class with a type attribute, as follows:

@XStreamAlias("coin")
public class Coin {
    String type;
}

你有一个Coins类来构成一个硬币列表:

And you have a Coins class that constains a List of Coin:

@XStreamAlias("coins")
public class Coins{

    @XStreamImplicit
    List<Coin> coins = new ArrayList<Coin>();
}

注意注释。列表是隐含的,硬币类将显示为硬币。

Pay attention to the annotations. The List is Implicit and the Coins class will be shown as "coins".

输出将是:

<coins>
  <coin>
    <type>Gold</type>
  </coin>
  <coin>
    <type>Silver</type>
  </coin>
  <coin>
    <type>Bronze</type>
  </coin>
</coins>

这与你要求的不一样,但有一个原因。

It's not the same you asked for, but there is a reason.

首先,硬币只有一个属性,但我们不确定你想要显示的所有对象是否也只有一个属性。因此,我们需要告诉我们正在讨论哪个对象属性。

At first, coin have only one attribute, but we are not sure if all objects you want to show do have only one attribute too. So, we need to tell which object attribute we are talking about.

您还可以将Coin属性显示为XML属性,而不是字段。如下:

You can also show the Coin attributes as XML Attributes, not fields. As follows:

@XStreamAlias("coin")
public class Coin {
    @XStreamAsAttribute
    String type;

    Coin(String type) {
        this.type = type;
    }
}

这是输出:

<coins>
  <coin type="Gold"/>
  <coin type="Silver"/>
  <coin type="Bronze"/>
</coins>

希望有所帮助。

这篇关于List根元素的XStream别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆