简体   繁体   English

如何使用XStream为相同的类元素设置不同的别名

[英]How to set different alias for same class elements using XStream

How to set different alias for XML elements for same class elements using XStream? 如何使用XStream为相同类元素的XML元素设置不同的别名?

I have the following classes and would like to reuse Phone class to represent both homephone and workphone that would generate XML of the following format 我有以下类,并且想重用Phone类来表示将生成以下格式XML的家庭电话和工作电话

<customer>
  <id>222</id>
  <name>TestCustomer</name>
  <workPhone>
    <workPhoneNumber>12345678</workPhoneNumber>
    <workPhoneExtn>2345</workPhoneExtn>
  </workPhone>
  <workPhone>
    <workPhoneNumber>23456789</workPhoneNumber>
    <workPhoneExtn>2555</workPhoneExtn>
  </workPhone>
  <homePhone>
    <homePhoneNumber>222222222</homePhoneNumber>
    <homePhoneExtn>1234</homePhoneExtn>
  </homePhone>
</customer>

With the following code, I am able to set different alias only till the class level for homephone and workphone objects. 使用以下代码,我只能在家庭电话和工作电话对象的类级别之前设置不同的别名。

@XStreamAlias("customer")
public class Customer {

    private String id;
    private String name;    

    @XStreamImplicit(itemFieldName = "workPhone")
    private ArrayList<Phone> workPhones;

    @XStreamImplicit(itemFieldName = "homePhone")
    private ArrayList<Phone> homePhones;
}

public class Phone {
    private String number;
    private String extn;
}

With the above class definitions, I can only get the following XML structure: 使用上面的类定义,我只能得到以下XML结构:

<customer>
  <id>222</id>
  <name>TestCustomer</name>
  <workPhone>
    <number>12345678</number>
    <extn>2345</extn>
  </workPhone>
  <workPhone>
    <number>12345678</number>
    <extn>2355</extn>
  </workPhone>
  <homePhone>
    <number>222222222</number>
    <extn>1234</extn>
  </homePhone>
</customer>

I do not have clear understanding of whether Mappers or converters would help achieve this. 我对Mappers或转换器是否可以帮助实现这一目标尚不明确。

Can someone suggest if there is anyway to set the Phone's number and extension to take the alias "workphoneNumber", "workphoneExtn" / "homePhoneNumber", "homePhoneExtn" depending on the alias for its class? 有人可以建议是否根据其类别的别名将电话的号码和分机设置为别名“ workphoneNumber”,“ workphoneExtn” /“ homePhoneNumber”,“ homePhoneExtn”吗? It should both work during marshalling and unmarshalling. 它在编组和拆组期间均应工作。 Please suggest. 请提出建议。

Try this: 尝试这个:

xstream.alias("workPhone", Person.class);
xstream.alias("homePhone", Person.class);

xstream.aliasField("workPhoneNumber", Person.class, "number");
xstraem.aliasField("homePhoneNumber", Person.class, "number");

...

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

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