views:

218

answers:

2

I have some XML that I am de-serializing and all works fine apart from one of my properties in the serialized class is also a class for example; Person.Address.Postcode.

Address is a property in Person class but Address is a class with properties such as Postcode.

If the incoming XML does not contain Address information and deserialization takes place when I look at Person.Address this is null.

What I would like to happen is for Person.Address not to be null and have things like Postcode not null but empty strings.

I have tried the IsNullable=false attribute on the Address property but that does not work.

How is this possible?

+1  A: 

You can make Postcode into a property that returns a String.Empty if it is not set, otherwise the value. Or make it impossible for it to be set to a null in the set block. Also you can make it impossible for Address to be null by making it into a struct. In which case you could set Postcode to String.Empty in the parameterless constructor. Or you can have your class implement IDeserializationCallback and in the method OnDeserialization make your Address whatever you need.

private string _postcode;
public string Postcode 
{
    get
    {
        return  _postcode ?? String.Empty;
    }
    set
    {
        _postcode = value;
    }
}

or

private string _postcode = String.Empty;
public string Postcode 
{
    get
    {
        return  _postcode;
    }
    set
    {
        _postcode = value ?? String.Empty;
    }
}

I find the first option better because even if something inside the Address class sets it to null, it will never return null.

Yuriy Faktorovich
How can I neatly modify the Postcode property (below) to what you are suggestingpublic string Info { get; set; }
Jon
A: 

If you are using DataContract, just use the OnDesrialized Attribiute (or OnDeserializing, or whatever you like), on some method, in which specify what you want to happen.

Itay
there is no way to implement this functionality with theXmlSerializer
Jon