Thursday, April 28, 2011

JSON.Net Custom rule to serialize property

I faced a problem where I need to not serialize to Json a Property when the Property is either empty string or zero.

I have Json.Net library which can be download here http://json.codeplex.com/. Very robust library. I highly recommend using it when dealing with Json string.

Anyway, back to the issue, to solve this problem, we create a method on the class itself with the following prefix "ShouldSerialize" + "". So for example if the property name is MyString, the method would be like the following

public bool ShouldSerializeMyString()
{
return !string.IsNullOrEmpty(MyString);
}

References:
http://james.newtonking.com/

No comments:

Post a Comment