I have the following class
[DataContract(Namespace = "", Name = "VersionRange")]
public sealed class VersionRange
{
[DataMember(Name = "Lower")]
private readonly Version _lower;
[DataMember(Name = "Upper")]
private readonly Version _upper;
public VersionRange(Version lower, Version upper)
{
_lower = lower;
_upper = upper;
}
}
and I want it to de serialize from the following XML
<?xml version="1.0" encoding="utf-8"?>
<VersionRange>
<Lower>1.2.3.4</Lower>
<Upper>5.6.7.8</Upper>
</VersionRange>
I've tried to archive this by implementing IDataContractSurrogate but did not succeed at all. Whe I return typeof(string)
for typeof(Version)
in GetDataContractType
method deserialization fails and GetDeserializedObject method is not called.
So, Is there any chance to use standard Version class and get it deserialized from "a.b.c.d"
string?
One way to do this is to deserialize to a string property and then in the set
method for the property convert the value to a Version.
[DataMember(Name = "Lower")]
private string _lowerStr
{
set
{
_lower = new Version(value);
}
}
private Version _lower;
/// and the same for Upper.
I have seen this commonly used for parsing datetime values which might be supplied with obscure formatting