I am creating an app that fetches fuel prices from a web service. I want to deserialise the prices a IDictionary of Price objects with the fuel as the key (similar to this).
I had created a setter to do this but have since found out that the serialisation uses the Add method rather than the setter for lists. Is there a way of doing this using the serialisation API or will I have to write custom serialisation code?
The XML looks like this
<?xml version="1.0"?>
<prices>
<price fuel="Petrol">152.43</price>
<price fuel="Diesel">147.53</price>
</prices>
The code looks like this
[XmlRoot("prices")]
public class FuelPrices
{
private IDictionary<Fuel, Price> prices = new Dictionary<Fuel, Price>();
// This is used for serialising to XML
[XmlElement("price")]
public ICollection<Price> Prices
{
get
{
return prices.Values;
}
set
{
prices = new Dictionary<Fuel, Price>();
foreach (Price price in value)
{
prices[price.Fuel] = price;
}
}
}
// These properties are used to access the prices in the code
[XmlIgnore]
public Price PetrolPrice
{
get
{
Price petrolPrice;
prices.TryGetValue(Fuel.Petrol, out petrolPrice);
return petrolPrice;
}
}
[XmlIgnore]
public Price DieselPrice
{
get
{
Price dieselPrice;
prices.TryGetValue(Fuel.Diesel, out dieselPrice);
return dieselPrice;
}
}
}