简体   繁体   中英

Is it possible to implicitly add object fields to XML using XStream?

I have to convert a sorted set of objects of type Organization to an XML file. The said type contains, along with primitive types and String objects, other reference type objects.

Here are the fields of Organization :

String orgName;
double capital;
Individual generalDirector;
Investor investor;

Next comes Investor :

Individual name;
double sharesPercentage;

And finally Individual :

String firstName;
String lastName;

As you can see, both Organization and Investor contain references to objects of type Individual .

Problem is, I need both firstName and lastName displayed in XML for the Organization objects, and only lastName for the Investor objects, so omitting firstName completely wouldn't work.

I also want to omit the <'generalDirector'> and <'investor'> tags from the output, but leave their content in separate tags, as in:

    <organization>
        <orgName>Dummy Solutions</orgName>
        <capital>50000</capital>
        <dirFirstName>Jacob</dirFirstName>
        <dirLastName>Smith</dirLastName>
        <investor>
            <lastName>Johnson</lastName>
            <sharePercentage>5.13</sharePercentage>
        </investor>
    </organization>

But XStream converts it in the following way:

  <organization>
      <orgName>Dummy Solutions</orgName>
      <generalDirector>
          <firstName>Jacob</firstName>
          <lastName>Smith</lastName>
      </generalDirector>
      <capital>50000</capital>
      <investor>
          <name>
              <firstName>NotSpecified</firstName>
              <lastName>Johnson</lastName>
          </name>
          <sharesPercentage>5.13</sharesPercentage>
      </investor>
  </organization>

How can I get rid of the generalDirector and Investor's name tags without removing their content? I know there is a way to do it for Collections, but what about reference object fields?
And is there a way to display both firstName and lastName for Individual contained in Organization, but not in Investor ?

Turns out it is impossible to do it quite the way I originally imagined.

However, the solution to my problem comes in form of a custom Converter , which implements the Converter interface from XStream package. Inside such a converter one can specify a way to serialize/deserialize a particular class of objects.

Upon doing that the solution is as easy as registering the specified converter in the current XStream instance, like so:

XStream xstream = new XStream();
xstream.registerConverter(new YourCustomConverter());

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