Json.NET - Conditional Serialization

In the last post, I have showb you how to use DataMember and JsonIgnore attributes for skipping properties from getting outputed to json. But in some case we need to omit it based on conditions and these apporaches is not to going to help you

In Json.NET we can do this by adding a method whose name will start with ShouldSerializeMethod and append the name of the property to it.

In the following example I have a class with two properties, Username and Password and I didn't want the password to be sent across. So I created a method ShouldSerializePassword(ShouldSerialize + name of the property that needs to be omitted).

So by manipulating the return value of the method, we can conditionally skip members from the resulting json.


No Comments

Add a Comment