Home > Blockchain >  C# XML Deserialize ignore Default value attribute
C# XML Deserialize ignore Default value attribute

Time:05-17

I am having a class with a set of properties that I use as user level settings. Each property has a Default Value attribute. Few has XmlIgnore attribute to avoid the serialization.

When serializing this class object as memory stream and it writes it correct, but while de-serializing it actually creates an object with all the properties default value which was not part of the serialized object. How can I ignore this default value initialization for few properties? Thanks in advance.

XmlSerializer serializer = new mlSerializer(typeof(DisplayPreferences));
DisplayPreferences newPrefs = null;
MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(prefs));
newPrefs = (DisplayPreferences)serializer.Deserialize(ms);
if (newPrefs != null)
{
   newPrefs.CopyTo(Editor.prefs);
}

This app is built in .NET 4.6 (winforms)

CodePudding user response:

Welcome to stackoverflow.

You've given very little information on how you are de-serializing them (a code snippet would help), but I assume you are de-serializing them into a typed object. If that is the case, then what you are experiencing is standard behavior. That is the whole point of the default value, you can't "partially de-serialize a typed object".

What you can do however is either:

  • de-serializing the object into a raw xmlObject, and write a custom serializer for it.

  • Make the properties nullable, this is typically where DTO's are useful.See below.

     public class SomeTypedObjectDTO
     {
           public Guid? NullableGuid { get; set; }
           public int? NullableInt { get; set; }
     }
    

----UPDATE----

I tired to keep this in line with your code. Lets say you have the following object.

public class DisplayPreferences
{
   public Guid Id { get; set; }
   public string Name { get; set; }
   public int Level { get; set; }
   public bool CanDisplay { get; set; }
}

And lets say you only want to serialize the "CanDisplay" and the "level" properties. You can create a DTO (Data Transfer object) for it, which is basically a stripped down version of the original object.

DTO:

public class DisplayPreferencesDTO
{
    public int Level { get; set; }
    public bool CanDisplay { get; set; }
}

Then I believe all you need to do is change the generic typeof() to use the DTO instead of the actual object.

XmlSerializer serializer = new mlSerializer(typeof(DisplayPreferencesDTO));

You can then map the DTO back to the original object when you like and if you like. You can either do this mapping manually or use a framework called Automapper. Automapper was explicitly designed for mapping DTO's.

If you need me to clarify anything let me know.

Happy coding!

CodePudding user response:

You may want to make them as null? just make them to nullable prop such as make a int to int?

  • Related