Assuming we have a JSON object similar to:
{
'12345': 'text string',
'rel': 'myResource'
}
Constructing a DataContract to map to this type seems fairly simple such as:
[DataContract]
MyResource
{
[DataMember(Name = "12345")]
public string SpecialValue { get; set; }
[DataMember(Name = "rel")]
public string Rel { get; set; }
}
Now the problem arrives that the name of the property is variable so it not guaranteed to be '12345'. Since this variable cannot be properly mapped using attributes it won't get picked up when using DataContractJsonSerializer.
If I change the class to support IExtensibleDataObject, I can get the value portion but not the property name which is a problem. I'm looking to maintain this value during deserialization/serialization in order to be able to send the information on a return request. I'm not looking to change over to using Json.NET to solve this problem as I want to know if it is possible in some form without resorting to an external dependency.
It's a little ugly, but it turns out you can use an
IDataContractSurrogate
to deserialize the class with the variably named property into aDictionary<string, object>
and then copy the values from the dictionary into your class. Of course, you will need to add another property to your class to hold the name of the "special" property.Here is an example surrogate that I was able to get working:
To use the surrogate, you'll need to create an instance of
DataContractJsonSerializerSettings
and pass it to theDataContractJsonSerializer
with the following properties set. Note that since we require theUseSimpleDictionaryFormat
setting, this solution will only work with .Net 4.5 or later.Note also that in your class you should NOT mark the "special" properties with a
[DataMember]
attribute, since they are handled specially in the surrogate.Here is a demo:
Output: