Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyCustomContractResolver : DefaultContractResolver
- {
- protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
- {
- JsonProperty property = base.CreateProperty(member, memberSerialization);
- property.ShouldSerialize = (instance => containsSomeValues(instance.GetType()
- .GetProperty(member.Name)
- .GetValue(instance, null)));
- return property;
- }
- private bool containsSomeValues(object p)
- {
- if (p == null)
- {
- return false;
- }
- if (p.GetType() == typeof(DateTime))
- {
- return true;
- }
- if (p.GetType() == typeof(string))
- {
- if (String.IsNullOrEmpty(p.ToString()))
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- /*
- * This block skips serialization of the empty list and lists with empty objects;
- * I'd like to serialize both of those as the empty array so it's commented out.
- *
- if (typeof(IEnumerable).IsAssignableFrom(p.GetType()))
- {
- bool containsValues = false;
- foreach (object o in (IEnumerable)p)
- {
- if (containsSomeValues(o))
- {
- containsValues = true;
- }
- }
- return containsValues;
- }
- */
- if (p.GetType().GetProperties().Count() > 0)
- {
- foreach (PropertyInfo pi in p.GetType().GetProperties())
- {
- if (containsSomeValues(pi.GetValue(p, null)))
- {
- return true;
- }
- }
- return false;
- }
- return true;
- }
- }
Add Comment
Please, Sign In to add comment