Showing posts with label serialization. Show all posts
Showing posts with label serialization. Show all posts

9 February 2012

ShouldSerialize

Sometimes features are staring at you in the face, all you need to do is read the docs. Other times it really feels like things are hidden. Thanks Con for pointing me to ShouldSerializePropertyName - I did a careful look through the MSDN serialization docs in hope of finding this very feature, but didn't have any luck.

What does it do? For any given property, create a bool ShouldSerializePropertyName() method to decide if it should be included in serialization. A bit magical, but does the trick.

Why do I want this? I want to serialize an object graph to XML. But I don't want to render a container element for any empty collections. I think I'm becoming a bit of a pedent when it comes to XML.

Docs (in as much as I could be find any) are over here under Windows Form Controls.

15 January 2012

XmlSerializer inheritance woes

OK, this just drove me crazy for about an hour. I'm using the XmlSerializer, and my object graph has derived types.

I was using the XmlInclude attribute in the correct manner, but I still kept getting:

The type Child was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

It didn't work when I passed the extraTypes parameter to the XmlSerializer constructor either.

In the end it turns out that the 'Namespace' declaration was the problem. Adding an identical namepsace to the Child class fixed the problem. Strange because up until using inheritance things have worked fine only specifying it on the root class.

[XmlRoot(Namespace = "somenamespace")]
public class Root
{
public Parent Field { get; set; }
}

[XmlInclude(typeof(Child))]
public class Parent
{
public string Data { get; set; }
}

public class Child : Parent
{
}

...
Root r = new Root();
r.Field = new Child();