Advertisement
uraharadono

JSON extension

Oct 19th, 2016
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | None | 0 0
  1. //using Newtonsoft.Json;
  2. //using Newtonsoft.Json.Serialization;
  3.  
  4.  
  5. public static class JsonExtensions
  6.     {
  7.         public static string ToJson(this object obj)
  8.         {
  9.             //as seen on http://www.newtonsoft.com/json/help/html/contractresolver.htm
  10.             //return JsonConvert.SerializeObject(obj, Formatting.Indented,
  11.             //    new JsonSerializerSettings
  12.             //    {
  13.             //        ContractResolver = new CamelCasePropertyNamesContractResolver()
  14.             //    });
  15.  
  16.             //same code written a little bit more clearly
  17.             JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings();
  18.             jsonSerializerSetting.ContractResolver = new CamelCasePropertyNamesContractResolver();
  19.            
  20.             return JsonConvert.SerializeObject(obj,Formatting.Indented, jsonSerializerSetting);
  21.         }
  22.         // Usage: responseJson.ToObject<List<object>>();
  23.         public static T ToObject<T>(this string jsonString)
  24.         {
  25.             return (T)JsonConvert.DeserializeObject<T>(jsonString);
  26.         }
  27.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement