1

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.

i3arnon
  • 113,022
  • 33
  • 324
  • 344
Pratap Das
  • 504
  • 2
  • 7
  • 20

4 Answers4

0

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?

Community
  • 1
  • 1
Mathieson
  • 1,698
  • 2
  • 17
  • 19
  • Seems like this is more task than putting attribute on every properties ! – Pratap Das Nov 13 '13 at 22:25
  • Like everything, the answer is 'it depends'. Is your object model going to change frequently? Will it be consumed by .NET code, and have KnownTypes data available, or are you going to be reusing abstractions in other layers (I'm thinking Xamarin here, which can't always figure out DataContracts well)? Will this system exist in relative isolation, or will you want to reuse parts? – Mathieson Nov 18 '13 at 21:08
0

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.

m27
  • 79
  • 1
  • 9
0

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.

i3arnon
  • 113,022
  • 33
  • 324
  • 344
0

From dotnet 4.0 and above,

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

Sushil
  • 2,837
  • 4
  • 21
  • 29
Ritesh Kumar
  • 153
  • 12