Search code examples
javaxmlxml-parsingxml-serializationxstream

Populating list values using xstream


I am working with Xstream to read some xml in the following format

 <Objects>  
  <Object Type="System.Management.Automation.Internal.Host.InternalHost">   
    <Property Name="Name" Type="System.String">ConsoleHost</Property>   
    <Property Name="Version" Type="System.Version">2.0</Property>   
    <Property Name="InstanceId" Type="System.Guid">7e2156</Property>
  </Object> 
</Objects> 

Basically under Objects tag there can be n number of Object Type and each Object Type can have n number of Property tags. So I have modelled by Java classes and the code to read it as follows

 @XStreamAlias("Objects")
class ParentResponseObject {
    @XStreamImplicit
    List <ResponseObject>responseObjects = new ArrayList<ResponseObject>(); 
    public String toString () {
        return responseObjects.get(0).toString();       
    }   
}
@XStreamAlias("Object")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "value" })
class ResponseObject {
    @XStreamAsAttribute
       String Type;
       String value;
       @XStreamImplicit
       List <Properties> properties = new ArrayList<Properties>();  
      public String toString () {
        return Type+" value is "+"List is "+properties+ value;      
    }   
}
@XStreamAlias("Property")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "value" })
class Properties {
    @XStreamAsAttribute
    String Name;
    @XStreamAsAttribute
    String Type;
    String value;
    Properties (String name, String type,String value) {
            this.Name = name;
            this.Type = type;
            this.value =  value;
        }   
}

Using this code, I am able to populate the responseObjects List in the ParentResponseObject class. However, the properties List in the ResponseObject is always null and is not getting populated , even though I am using the same technique in both the cases. I have debugged a lot but could not find anything. Your help and guidance is solicited.


Solution

  • Add reference to the implicit it will work

      @XStreamImplicit(itemFieldName="Object")
      List<ResponseObject> responseObjects = new ArrayList<ResponseObject>();
    
      @XStreamImplicit(itemFieldName="Property")
      List<Properties> properties = new ArrayList<Properties>();