I am trying to write classes for deserializing an XML response from some API.
Here is a sample response. When I query for ObjectA,
<Response>
<Status>0</Status>
<Message>Ok</Message>
<Data>
<ObjectAs>
<Count>2</Count>
<ObjectA>...</ObjectA>
<ObjectA>...</ObjectA>
</ObjectAs>
</Data>
</Response>
When I query for ObjectB,
<Response>
<Status>0</Status>
<Message>Ok</Message>
<Data>
<ObjectBs>
<Count>1</Count>
<ObjectB>...</ObjectB>
</ObjectBs>
</Data>
</Response>
I am trying to create a generic Response class, but everything I tried seems to be futile.
I can't change the response structure. And I am trying to avoid writing a new Response class for each of the response type.
Notice how under Data, each API response is different. For ObjectA it is <ObjectAs>
and for ObjectB it is <ObjectBs>
.
Here is my ApiResponse class,
[XmlRoot(ElementName = "Response")]
public class ApiResponse<T>
{
public int Code { get; set; }
public string Message { get; set; }
[XmlAnyElement("Data")]
public XmlElement DataElement { get; set; }
[XmlIgnore]
public List<T> Data
{
get
{
{
return null; // How do I parse and return the list of Objects (A, B, C, whatever?)
}
}
}
}
Here is my sample API XML response, when I query for devices.
<Response>
<Code>0</Code>
<Message>OK</Message>
<Data>
<Devices>
<Count>2</Count>
<Device>
<Name>0001</Name>
<Active>TRUE</Active>
<DeviceType>1</DeviceType>
<Address>192.168.0.75</Address>
<Port>80</Port>
<Memo/>
</Device>
<Device>
<Name>0002</Name>
<Active>TRUE</Active>
<DeviceType>1</DeviceType>
<Address>192.168.0.78</Address>
<Port>80</Port>
</Device>
</Devices>
</Data>
</Response>
And when I query for users,
<Response>
<Code>0</Code>
<Message>OK</Message>
<Data>
<Users>
<Count>1</Count>
<User>
<Name>Administrator</Name>
<Group>Admins</Group>
</User>
</Users>
</Data>
</Response>