DataContractSerializer is an opt-in serializer. How to make it Opt-Out?

时间秒杀一切 提交于 2019-11-27 16:27:23
Mathieson

It depends if your properties can be automatically generated - if so, you could simple substitute the WCF serializer. Usually this is done to use JSON.NET instead:

C# WCF REST - How do you use JSON.Net serializer instead of the default DataContractSerializer?

That is how it was designed as indicated on this MSDN link here . Another alternative is using XmlSerializer which serializes all public fields/properties. Ultimately, you'll have to weigh the pros-and-cons on considering DataContractSerializer vs another approach.

You can simply not mark your classes with any of the common serialization attributes (i.e. [DataContract]/[Serializable]) and make sure all the properties you want to serialize are public get and set. If you want to exclude a certain property you need to mark it with the [IgnoreDataMember] attribute.

Example:

public class Hamster
{
    public string Name { get; set; }
    [IgnoreDataMember]
    public int Age { get; set; }
}

From Serializable Types on MSDN:

You can apply the DataContractAttribute and DataMemberAttribute attributes... However, even types that are not marked with these attributes are serialized and deserialized. The following rules and exceptions apply: ...
All public fields, and properties with public get and set methods are serialized, unless you apply the IgnoreDataMemberAttribute attribute to that member.

Ritesh Kumar

From dotnet 4.0 and above,

You can avoid the [DataContract] attribute to make all the public datamembers serializable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!