Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization no null values

Lets say i have a class

    [Serializable()]
public class Car
{
    public string model;
    public int year;
}

I serialize that to disk named "car.xx". Then i add a property to my Car class so it will be like this:

    [Serializable()]
public class Car
{
    public string model;
    public int year;
    public string colour;
}

Then i deserialize "car.xx" ( that contains 2 fields ) to my current car class that contains 3 fields, which will make the "colour" property of our Car class null.

How do i set that "new properties" dont get null values? Setting them in the constructor wont help.

I am using BinaryFormatter serializer

I want string values that are null to be replaced with ""

like image 250
syncis Avatar asked Jun 17 '11 14:06

syncis


2 Answers

if you are not using XmlSerializer then consider using OnDeserializedAttribute, OnSerializingAttribute, OnSerializedAttribute, and OnDeserializingAttribute attributes

see this.

like:

[Serializable()]
public class Car
{
    public string colour;
    public string model;
    public int year;

    [OnDeserialized()]
    internal void OnDeserializedMethod(StreamingContext context)
    {
       if (colour == null)
       {
           colour = string.Empty;
       }
    }
}
like image 147
Jalal Said Avatar answered Sep 23 '22 05:09

Jalal Said


It all depends on the serializer.

Some serializer skip constructors; some serializers run the default constructor. Some let you choose. Some offer serialization callbacks.

So depending on the serializer:

  • write a public parameterless constructor to set a default value (or use a field-initializer, which is ultimately similar)
  • write an "on deserializing" serialization callback to set a default before deserialization

or worst-case, implement custom serialization (ISerializable / IXmlSerializable / etc, depending on the serializer)

For example, with BinaryFormatter:

[Serializable]
public class Car : IDeserializationCallback
{
    public string model;
    public int year;
    public string colour;
    void IDeserializationCallback.OnDeserialization(object sender)
    {
        if (colour == null) colour = "";
    }
}

With other serializers, it might use [OnDeserialized] instead. Note; personally I wouldn't be exposing public fields, even in a DTO. But if you are using BinaryFormatter, changing this is now a breaking change. For completeness, I also wouldn't be using BinaryFormatter - it is not very friendly to this. Other serializers are available that will hurt you less.

like image 38
Marc Gravell Avatar answered Sep 25 '22 05:09

Marc Gravell