Implementing IXmlSerializable Requires Collection Property to Have Setter - c#

I have a collection property that is of a custom type which inherits from BindingList. Currently, this property gets serialized via XmlSerializer even though it has no Setter. I now am trying to implement IXmlSerializable on this custom collection class and see that the WriteXml() and ReadXml() interface methods only get called if my collection property has a Setter. Why does serialization ignore this property now unless there is a Setter when before it serialized correctly without one.
To Reproduce:
First, have a class called "Item":
public class Item
{
public Item() {}
// Generates some random data for the collection
private MyCollectionType GenerateContent()
{
Random ranGen = new Random();
MyCollectionType collection = new MyCollectionType();
for (int i = 0; i < 5; i ++)
{
collection.Add("Item" + ranGen.Next(0,101));
}
return collection;
}
public MyCollectionType Items
{
get
{
if (m_Items == null)
{
m_Items = GenerateContent();
}
return m_Items;
}
}
private MyCollectionType m_Items = null;
}
Next have create the collection Class "MyCollectionType" (Note that IXmlSerializable is purposely missing in the snippet to start off with):
public class MyCollectionType : BindingList<string>
{
public MyCollectionType()
{
this.ListChanged += MyCollectionType_ListChanged;
}
void MyCollectionType_ListChanged(object sender, ListChangedEventArgs e){ }
public MyCollectionType(ICollection<string> p)
{
this.ListChanged += MyCollectionType_ListChanged;
}
#region Implementation of IXmlSerializable
public void WriteXml(XmlWriter writer)
{
throw new NotImplementedException();
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public XmlSchema GetSchema() { return null; }
#endregion
}
Lastly, add some code in Main() to Serialize and Deserialize an "Item":
Item myItem = new Item();
Item newItem = null;
// Define an XmlSerializer
XmlSerializer ser = new XmlSerializer(typeof(Item));
// Serialize the Object
using (TextWriter writer = File.CreateText(#"c:\temporary\exportedfromtest.xml"))
{
ser.Serialize(writer,myItem);
}
// Deserialize it
using (Stream reader = new FileStream(#"c:\temporary\exportedfromtest.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateTextReader(reader, XmlDictionaryReaderQuotas.Max))
{
newItem = (Item)ser.Deserialize(xmlDictionaryReader);
}
}
So, if you run that as-is you should see that it serializes and deserializes without a Setter. Currently, the collection doesn't list "IXmlSerializable" in the snippet above, but the methods are there. So if you now go back and add "IXmlSerializable" to the MyCollectionType class and run again you will notice that the collection property isn't serialized and the WriteXml() and ReadXml() methods don't get called. Also note that if you add an empty Setter those methods will suddenly get called.

This is the documented behavior. It is explained, albeit unclearly, in Introducing XML Serialization:
XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.
As you can see, get-only properties are in general not serialized -- except for read-only collections. But what does Microsoft mean by this? A collection is not a property after all.
What they mean is as follows:
XML serialization does not convert get-only properties or read-only fields (except get-only collection-valued properties with pre-initialized collections).
(Incidentally, this means that, if you add items to your collection in the containing type's constructor, then serialize and deserialize it, the default items will get duplicated. For an explanation of why, see XML Deserialization of collection property with code defaults. If I deserialize your Item class I see this behavior.)
How does this apply in your case? Well, when you make your collection implement IXmlSerializable, the serializer no longer interprets it as a collection; it interprets it as a black box. Thus its special rules for collections no longer apply. The property referring to your collection must now be read/write; XmlSerializer will construct an instance itself, deserialize it, and set it into its parent just like any other non-collection property value.

Related

Serialize entire JSON object, but skip single property when deserializing

When serializing an object, I have a List<T> property where T is an abstract type which I'd like to serialize naturally. However, when deserializing the object, I want/need to manually deserialize this abstract list. I'm doing the latter part with a custom JsonConverter which looks at a property on each item
in the list and then deserializes it to the correct type and puts it in the list.
But I also need to deserialize the rest of the object, without doing it property-by-property. Pseudo-code follows.
MyObject
class MyObject {
public Guid Id;
public string Name;
public List<MyAbstractType> Things;
}
MyObjectConverter
class MyObjectConverter : JsonConverter {
public override object ReadJson(reader, ..., serializer) {
// Line below will fail because the serializer will attempt to deserlalize the list property.
var instance = serializer.Deserialize(reader);
var rawJson = JObject.Load(reader); // Ignore reading from an already-read reader.
// Now loop-over and deserialize each thing in the list/array.
foreach (var item in rawJson.Value<JArray>(nameof(MyObject.Things))) {
var type = item.Value<string>(nameof(MyAbstractType.Type));
MyAbstractType thing;
// Create the proper type.
if (type == ThingTypes.A) {
thing = item.ToObject(typeof(ConcreteTypeA));
}
else if (type == ThingTypes.B) {
thing = item.ToObject(typeof(ConcreteTypeB));
}
// Add the thing.
instance.Things.Add(thing);
}
return instance;
}
}
To recap, I want to manually handle the deserialization of Things, but allow them to naturally serialize.

Serialize to XML an object that contains IList

So I have an Object called FormType.
It contains some strings, booleans etc.
But FormType also contains this:
private IList<FormTypeVersion> _versions = new List<FormTypeVersion>();
public virtual IList<FormTypeVersion> Versions
{
get { return _versions; }
set { _versions = value; }
}
Is this why I am getting this error:
{"Cannot serialize member 'Domain.FormType.Versions' of type 'System.Collections.Generic.IList`1
Also - FormTypeVersion also contains some ILists.
How can I get round this error, it happens at this line:
var xm = new XmlSerializer(typeof(T));
The XmlSerializer cannot deserialize interfaces (unless you want to implement IXmlSerializable yourself on the FormType object). That is why you are seeing that exception.
If you change your IList to List it should work like in the following example:
[Serializable]
public class FormType
{
private List<FormTypeVersion> _versions = new List<FormTypeVersion>();
public virtual List<FormTypeVersion> Versions
{
get { return _versions; }
set { _versions = value; }
}
}
If you don't have the luxury to change your type from IList to List, then the cleanest approach is to implement IXmlSerializable. There are other solutions using abstract types, reflection and similar, but i wouldn't call that clean.

DataContractJsonSerializer not serializing properly

I am trying to serialize some data which contains an observable collection of objects and write it into a text tile. My output is [] and I do now know where I have made a mistake.
my object code
public class ObjectList : ObservableCollection<string>, INotify...
{
public ObservableCollection<string> ObjectListInstance = new ObservableCollection<string>();
public string Name;
... get set methods & property changed method
}
my IO code
using (Stream newStream = await Windows.Storage.ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("file.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting))
{
DataContractJsonSerializer newDataContractJsonSerializer = new DataContractJsonSerializer(typeof(ObservableCollection<ObjectList>));
newDataContractJsonSerializer.WriteObject(newStream, ObjectList);
}
my code stub
ObjectList newObjectList = new ObjectList();
newObjectList.Name = "AAA NAME";
newObjectList.ObjectListInstance.Add("ITEM 1");
newObjectList.ObjectListInstance.Add("ITEM 2");
bool status = await IOClass.IO.WriteCategory(newObjectList);
You can't have a class that is both a collection and has additional properties to be serialized. However, you can have a class that contains a list and has additional properties, which is what I think you are trying to do here. To make it work you will need to make some adjustments to your code:
Your ObjectList should not inherit from ObservableCollection<T> (or any other list type)
You must mark your class with [DataContract], and mark the properties/fields you want to be serialized with [DataMember].
When you create your DataContractJsonSerializer instance, pass to the constructor the top-level type you want to serialize. In your case, this should be ObjectList, not ObservableCollection<ObjectList>.
When you call WriteObject on the serializer, the second parameter should be the object instance you are serializing, not a Type.
Here is the corrected class:
[DataContract]
public class ObjectList
{
[DataMember]
public ObservableCollection<string> ObjectListInstance = new ObservableCollection<string>();
[DataMember]
public string Name;
}
Here is the corrected serialization code:
DataContractJsonSerializer newDataContractJsonSerializer =
new DataContractJsonSerializer(typeof(ObjectList));
newDataContractJsonSerializer.WriteObject(newStream, newObjectList);
With these changes you should get the following JSON output:
{"Name":"AAA NAME","ObjectListInstance":["ITEM 1","ITEM 2"]}

Serialize T that contains List<T>

I want to serialize a MyClass, which is a class that contains a list MyClass.
In the XML, I want to write only myClass.Name, then when I deserialize it, I then find which MyClass should be in which other MyClass. I have the following code that properly serializes the list of MyClass into a list of string. However, it doesn't deserialize the list of string.
//List of actual object. It's what I use when I work with the object.
[XmlIgnore]
public List<TaskConfiguration> ChildTasks { get; set; }
//Used by the serializer to get the string list, and used
//by the serializer to deserialize the string list to.
[XmlArray("ChildTasks")]
public List<string> ChildTasksSurrogate
{
get
{
List<string> childTaskList = new List<string>();
if (ChildTasks != null)
childTaskList.AddRange(ChildTasks.Select(ct => ct.Name).ToList());
if (_childTasksSurrogate != null)
childTaskList.AddRange(_childTasksSurrogate);
//Clears it not to use it when it serializes.
_childTasksSurrogate = null;
return childTaskList;
}
set
{
_childTasksSurrogate = value;
}
}
[XmlIgnore]
private List<string> _childTasksSurrogate;
As I said, the serialization works. The problem lies with the deserialization. After the deserialization, MyClass._childTasksSurrogate is null.
The problem was related to HOW does the XmlSerializer deserializes the Xml :
I thought that the XmlSerializer would assign the whole property (read: myList = DeserializedList), while it looks like it adds all the elements (read: myList.AddRange(DeserializedList).

XmlSerializer error Serializing Interface Objects

I have a list of objects that implement a common interface. If I try to simply serialize it I get a nice exception that tells me that the serializer cannot serialize interfaces:
private readonly ObservableCollection<ICanHasInterface> children = new ObservableCollection<ICanHasInterface>();
public ObservableCollection<ICanHasInterface> Children
{
get { return children; }
}
=> "Cannot serialize member ... of type ... because it is an interface"
Apparently asking the serializer to get the type of the objects and mark the XmlElement with the attribute xsi:type (which is done if an object inherits from another class) is too much.
So because I do not want to implement IXmlSerializable, I thought up a workaround which looked promising initially:
private readonly ObservableCollection<ICanHasInterface> children = new ObservableCollection<ICanHasInterface>();
[XmlIgnore()]
public ObservableCollection<ICanHasInterface> Children
{
get { return children; }
}
[XmlElement("Child")]
public List<object> ChildrenSerialized
{
get
{
return new List<object>(Children);
}
set
{
Children.Clear();
foreach (var child in value)
{
if (child is ICanHasInterface) AddChild(child as ICanHasInterface);
}
}
}
With this at least the serialisation works just fine (Note: Either specify XmlInclude attributes for the types that can be in the original list or hand over an array of types in the constructor of the serializer), however if the object is deserialized the Children collection ends up empty because the set block is never reached during deserialization, I am quite clueless as to why this is; any ideas?
On deserialization the serializer uses your property getter to get the collection instance and then calls Add() on it for each item. It does not call your property setter. Something like this:
YourClass c = new YourClass();
c.ChildrenSerialized.Add(ReadValue());
...
In order to keep the collections synchronized you'd need to customize the Add() behavior of the collection you return from the property getter.
A better option is to change the ChildrenSerialized property to use an object[]. For arrays, the serializer reads the value into an array and then calls your property setter with the value.

Categories

Resources