Advertisement
Capaj

How to serialize only SOME properties of an object JSON.NET

Jan 6th, 2013
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Serialization;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace showcase_json.net_filtering_serialization
  10. {
  11.     class serializationTestClass {
  12.         public int testPropOne { get; set; }
  13.         public DateTime testPropTwo { get; set; }
  14.         public string testPropThree { get; set; }
  15.  
  16.     }
  17.  
  18.     class Program
  19.     {
  20.         static void Main(string[] args)
  21.         {
  22.             var testIntance = new serializationTestClass() { testPropOne = 28, testPropTwo = DateTime.Now, testPropThree = "hello world" };
  23.             var settings = new JsonSerializerSettings() { ContractResolver = new CriteriaContractResolver<serializationTestClass>(new List<string>() { "testPropTwo", "testPropThree" }) };
  24.             var serialized = JsonConvert.SerializeObject(testIntance, settings);
  25.             Console.WriteLine(serialized);
  26.             Console.ReadKey();
  27.         }
  28.     }
  29.  
  30.     //<summary>
  31.     //json.net serializes ALL properties of a class by default
  32.     //this class will tell json.net to only serialize properties if
  33.     //they MATCH the list of valid columns passed through the querystring to criteria object
  34.     //</summary>
  35.     public class CriteriaContractResolver<T> : DefaultContractResolver
  36.     {
  37.         List<string> _properties;
  38.  
  39.         public CriteriaContractResolver(List<string> properties)
  40.         {
  41.             _properties = properties;
  42.         }
  43.  
  44.         protected override IList<JsonProperty> CreateProperties(Type cType, MemberSerialization memberSerialization)
  45.         {
  46.             IList<JsonProperty> filtered = new List<JsonProperty>();
  47.  
  48.             foreach (JsonProperty p in base.CreateProperties(cType, memberSerialization))    //fix this problem
  49.             {
  50.                 if (_properties.Contains(p.PropertyName))
  51.                     filtered.Add(p);
  52.  
  53.             }
  54.             return filtered;
  55.  
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement