Search code examples
javaxstreamstax

How to alias the data type using XStream?


I want to convert the object in to xml where it requires to give the alias for String data type. For example:

public class ArrayTest
{
   private int id=4;
   public String area[];
   public void setArea(String ar[])
  {
    area = ar;
  }
}

Object to xml Conversion class is like:

public class Test
{
  public static void main(String args[])
  {
       String area[] = {"ABC","XYZ","PRQ"};
       ArrayTest at = new ArrayTest();
       at.setArea(area);
       Xstream stream = new XStream(new staxDriver());
       stream.alias("response",ArrayTest.class);
       System.out.println(stream.toXML(at));
  }
}

I'm getting output as :

<?xml version="1.0" ?>
<response>
  <id>4</id>
  <area>
    <string>ABC</string>
    <string>XYZ</string>
    <string>PRQ</string>
  </area>
</response>

But I want out output as:

<?xml version="1.0" ?>
<response>
  <id>4</id>
  <area>
    <code>ABC</code>
    <code>XYZ</code>
    <code>PRQ</code>
  </area>
</response>

I'm new to XStream, Kindly help me out


Solution

  • I think this could work:

    First add a getter for area

    public class ArrayTest {
        private int id = 4;
        private String[] area; 
    
        public void setArea(String ar[]) {
            area = ar;
        }
    
        public String[] getArea() { 
            return area;
        }
    }
    

    Then add a NamedArrayConverter Converter:

    public static void main(String args[]) {
        String area[] = { "ABC", "XYZ", "PRQ" };
        ArrayTest at = new ArrayTest();
        at.setArea(area);
        XStream stream = new XStream();
        stream.alias("response",ArrayTest.class);
        stream.registerConverter(new NamedArrayConverter(at.getArea().getClass(), null, "code"));
        System.out.println(stream.toXML(at));
    }
    

    This is the output:

    <response>
      <id>4</id>
      <area>
        <code>ABC</code>
        <code>XYZ</code>
        <code>PRQ</code>
      </area>
    </response>