Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Newtonsoft.Json;
- using Newtonsoft.Json.Serialization;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace showcase_json.net_filtering_serialization
- {
- class serializationTestClass {
- public int testPropOne { get; set; }
- public DateTime testPropTwo { get; set; }
- public string testPropThree { get; set; }
- }
- class Program
- {
- static void Main(string[] args)
- {
- var testIntance = new serializationTestClass() { testPropOne = 28, testPropTwo = DateTime.Now, testPropThree = "hello world" };
- var settings = new JsonSerializerSettings() { ContractResolver = new CriteriaContractResolver<serializationTestClass>(new List<string>() { "testPropTwo", "testPropThree" }) };
- var serialized = JsonConvert.SerializeObject(testIntance, settings);
- Console.WriteLine(serialized);
- Console.ReadKey();
- }
- }
- //<summary>
- //json.net serializes ALL properties of a class by default
- //this class will tell json.net to only serialize properties if
- //they MATCH the list of valid columns passed through the querystring to criteria object
- //</summary>
- public class CriteriaContractResolver<T> : DefaultContractResolver
- {
- List<string> _properties;
- public CriteriaContractResolver(List<string> properties)
- {
- _properties = properties;
- }
- protected override IList<JsonProperty> CreateProperties(Type cType, MemberSerialization memberSerialization)
- {
- IList<JsonProperty> filtered = new List<JsonProperty>();
- foreach (JsonProperty p in base.CreateProperties(cType, memberSerialization)) //fix this problem
- {
- if (_properties.Contains(p.PropertyName))
- filtered.Add(p);
- }
- return filtered;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement