Reputation: 479
I am using the .net datacontractjsonserializer to serialize my list of objects to a JSON string, but there are certain public properties that I don't want to serialize, how to prevent the datacontractjsonserializer from serializing these properties?
Thanks
Upvotes: 2
Views: 1084
Reputation: 7895
There are two approaches when it comes to serializing with the .NET serializers:
White-listing of properties:
This is the recommenden approach. You mark your class explicitly with the DataContract
attribute. With this, only properties that are marked with the DataMember
attribute will be included in the output.
Instead of doing a black list of properties that you don't want to serialize, it's better to do a white list and mark all properties you DO want to be serialized. This is more safe, because it requires the developer to explicitly state that they want a property to be serialized when introducing a new property.
Black-listing of properties:
If you really want to do black listing, you can use the IgnoreDataMember
attribute as pointed out by others. In this case you don't need to (and shouldn't) mark your class with the DataContract
attribute. Instead you mark the properties you want to have excluded with IgnoreDataMember
.
I hope this helps a bit to explain the choices and their advantages/disadvantages.
Edit: Expanded my answer
Upvotes: 6
Reputation: 1218
There are two options, I can think of.
1- On the property try using [IgnoreDataMember] attribute.
2 - Do not mark your property with [DataMember] attribute.
Hope it helps
Upvotes: 2