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

老子叫甜甜 提交于 2019-11-26 18:38:59

问题


I inherited some classes with a large number of attributes. I want to be able to serialize them for WCF.

As DataContractSerializer is an opt-in serializer, I will need to decorate all the properties with DataMember attribute, which seems to me a little cumbersome. Don't I have any other way around so that I don't have to add DataMember to all the properties?

Please note, most of my properties need to be serialized.


回答1:


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?




回答2:


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.




回答3:


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.




回答4:


From dotnet 4.0 and above,

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



来源:https://stackoverflow.com/questions/19964866/datacontractserializer-is-an-opt-in-serializer-how-to-make-it-opt-out

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