1

I'm using YAXLib to serialize my objects, I find the following bug in the YAXLib source code:

If I try to serialize a dictionary that contains a null value I got a unhandled nullReference exception.

Dictionary<string, object> Dict= new Dictionary<string, object>();
Dict.Add("foo", null);
YAXSerializer serializer = new YAXSerializer(typeof (Dictionary<string, object>));
serializer.SerializeToFile(Dict, "path"); // << CRASH

Running deep in YAXSerializer.cs I found the following code:

foreach (object obj in dicInst) //dicInst is the Dict variable defined above
{
  ...
  // valueObj is null
  XElement addedElem = AddObjectToElement(elemChild, valueAlias, valueObj);
  ...
}

private XElement AddObjectToElement(XElement elem, XName alias, object obj)
{
  //obj is null and so obj.GetType() crash
  UdtWrapper udt = TypeWrappersPool.Pool.GetTypeWrapper(obj.GetType(), this);
  ...
}

Some of you faced the same problem? Is there a way to solve it?

Community
  • 1
  • 1
Rowandish
  • 2,655
  • 3
  • 31
  • 52
  • Seems like the mistake would be taken care of if you avoided adding null objects to your dictionary. Is there a reason you have those values? – Kateract Apr 06 '16 at 15:02
  • The xml is the representation of the user setting and I'd like to distinguish between empty string setting ("") and no setting at all (null) – Rowandish Apr 06 '16 at 15:05

1 Answers1

0

You can filter out the null objects so that they aren't fed into the serializer:

var newdata = data.Where(kvp => kvp.Value != null).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Or you can create a new object and set all null values to instances of that object:

var newdict = dict.Select(kvp => kvp = new KeyValuePair<string, object>(kvp.Key, kvp.Value == null ? new NullObject() : kvp.Value)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Kateract
  • 822
  • 6
  • 15