How can I prevent datamember serialization?

I only want to de-serialize a specific data item without serializing it.

I understand that I can set EmitDefaultValue = false and set to null.

But I also do not want to change the value of the data item, is there any other way to achieve it?

A serializer is a DataContractSerializer. :)

Thanks.

+6
source share
5 answers

You can change the value of the data item before serialization (to the default value, so it cannot be serialized), but then after serialization, you change it back - using the [OnSerializing] and [OnSerialized] callbacks (more information in this blog post ). This works great if you don't have multiple threads that serialize the object at the same time.

 public class StackOverflow_8010677 { [DataContract(Name = "Person", Namespace = "")] public class Person { [DataMember] public string Name; [DataMember(EmitDefaultValue = false)] public int Age; private int ageSaved; [OnSerializing] void OnSerializing(StreamingContext context) { this.ageSaved = this.Age; this.Age = default(int); // will not be serialized } [OnSerialized] void OnSerialized(StreamingContext context) { this.Age = this.ageSaved; } public override string ToString() { return string.Format("Person[Name={0},Age={1}]", this.Name, this.Age); } } public static void Test() { Person p1 = new Person { Name = "Jane Roe", Age = 23 }; MemoryStream ms = new MemoryStream(); DataContractSerializer dcs = new DataContractSerializer(typeof(Person)); Console.WriteLine("Serializing: {0}", p1); dcs.WriteObject(ms, p1); Console.WriteLine(" ==> {0}", Encoding.UTF8.GetString(ms.ToArray())); Console.WriteLine(" ==> After serialization: {0}", p1); Console.WriteLine(); Console.WriteLine("Deserializing a XML which contains the Age member"); const string XML = "<Person><Age>33</Age><Name>John Doe</Name></Person>"; Person p2 = (Person)dcs.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(XML))); Console.WriteLine(" ==> {0}", p2); } } 
+7
source

What serializer? If it is an XmlSerializer , then either:

 public int Foo {get;set;} [XmlIgnore] public bool FooSpecified { get { return false; } // never serialize set { } } 

or

 public int Foo {get;set;} public bool ShouldSerializeFoo() { return false; } 

will do it. A quick test shows that this does not work for the DataContractSerializer . protobuf-net also supports both of these options, for information.

+4
source

Have you tried decorating the [IgnoreDataMember] property?

+1
source

There is a System.Xml.Serialization.XmlIgnoreAttribute attribute that tells xmkserializers to ignore your property. But this only changes the behavior of xml serialization.

0
source

add IgnoreDataMemberAttribute

0
source

Source: https://habr.com/ru/post/900779/


All Articles