Sunday, August 20, 2017

Serialize Specific Properties of List using Newtonsoft.Json in .Net C#


/* Custom ContractResolver: The below contract resolver will help to serialize only those properties that will be defined in the resolver settings*/

public class DynamicContractResolver : DefaultContractResolver
    {
        private readonly List<string> _propertiesToSerialize;
        public DynamicContractResolver(string propertiesToSerialize = "")
        {
            var list = !string.IsNullOrEmpty(propertiesToSerialize) ? propertiesToSerialize.Split(',').ToList() : new List<string>();
            _propertiesToSerialize = list;
        }

        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var properties = base.CreateProperties(type, memberSerialization);
            properties = properties.Where(p => _propertiesToSerialize.Contains(p.PropertyName.ToLower())).ToList();
            return properties;
        }
    }



/* Entity */
public class TestClass
{
public int Id {get;set;}
public string Name {get;set;}
public string Age {get;set;}
}


/*
var list = new List<TestClass>();
list.Add(new TestClass { Id=1, Name ="Amit Jain",Age="31"});
list.Add(new TestClass { Id=2, Name ="Michael",Age="25"});
list.Add(new TestClass { Id=3, Name ="Robin",Age="26"});
*/


Now, Lets try to serialize only Name and Age:

Note: TO use below, one must include the Newtonsoft.Json reference into the project.

var data = JsonConvert.SerializeObject(list, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver("name,age") });


/* Here's the output of the Data String as Json*/

[
  {
    "Name": "Amit Jain",
    "Age": 31
  },
  {
    "Name": "Michael",
    "Age": 25
  },
  {
    "Name": "Robin",
    "Age": 26
  }
]


Try it..












No comments:

Post a Comment