简体   繁体   中英

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?

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

<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:

<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.

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? 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");

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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