1

Failing to deserialize an xml into a Struct which was created before by serializing a Class object before.

The Struct and the Class are defined with the same fields and decorated with DataMember attributes.

This is the XML emitted when serializing the Class at the server:

<?xml version="1.0"?>
<CacheItem xmlns="http://schemas.datacontract.org/2004/07/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <ProfileID>2</ProfileID>
  <CategoryID>3</CategoryID>
  <ID>1</ID>
  <SeverityID>4</SeverityID>
</CacheItem>

This is the Struct definition:

[DataContract] 
public struct CacheItem {
 [DataMember(Name = "ID")] public long ID;
 [DataMember(Name = "ProfileID")] public long ProfileID;
 [DataMember(Name = "CategoryID")] public int CategoryID;
 [DataMember(Name = "ServerityID")] public short SeverityID;
}

This is the code that tries to deserialize that XML into the Struct:

var dcs = new DataContractSerializer(typeof(CacheItem));
using(StreamReader sr = new StreamReader("OutputSerialization.txt", false)) {
 using(XmlDictionaryReader xdw = XmlDictionaryReader.CreateTextReader(sr.BaseStream, new XmlDictionaryReaderQuotas())) {
  CacheItem p = (CacheItem) dcs.ReadObject(xdw);
 }
}

The deserialized instance contains the correct value of ProfileID field, which is 2, and 0 for the other primitive fields (probably because 0 is the default value).

When changing the order of the fields in the XML and then deserializing into the Struct, the Struct instance has different fields loaded with the correct values.

It seems like deserializing into a Struct, the DataContractSerializer behaves differently, since if I change CacheItem type to Class, it works perfectly.

Note: The actual issue was spotted in our Client-Server communication, in which we use WCF. The code above is after I've isolated the issue.

Simon
  • 83
  • 7
  • 1
    `DataContractSerializer` is order sensitive, see [WCF Datacontract, some fields do not deserialize](https://stackoverflow.com/q/2519240) and [Data Member Order and XML Deserialization](https://stackoverflow.com/q/1262223) and [XML deserialization ignores properties out of alphabetical order](https://stackoverflow.com/q/35773293). It looks like the order of elements in your XML differs from the expected order. Perhaps you need to manually set the [data member order](https://stackoverflow.com/a/3816600)? – dbc Oct 28 '18 at 21:00
  • Thanks a lot @dbc, that explains it. – Simon Nov 19 '18 at 09:05

0 Answers0