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
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
DataContractattribute. With this, only properties that are marked with theDataMemberattribute 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
IgnoreDataMemberattribute as pointed out by others. In this case you don’t need to (and shouldn’t) mark your class with theDataContractattribute. Instead you mark the properties you want to have excluded withIgnoreDataMember.I hope this helps a bit to explain the choices and their advantages/disadvantages.
Edit: Expanded my answer