. 1 public class JsonHelper 2 { . 3 . 4 #region Json serialization and deserialization . 5 . 6 /// <Summary> . 7 /// the objects into json 8 /// (required in advance consistent good structure configured Model data acess , the same name and the data field may be acess) . 9 /// </ Summary> 10 /// <typeParam name = "T"> Object type </ typeParam> . 11 /// <param name = "JSON"> Json character string </ param> 12 is /// <Returns> </ Returns> 13 is public T ConvertJsonToObject <T>(string json) 14 { 15 the try 16 { . 17 the DataContractJsonSerializer Serializer = new new the DataContractJsonSerializer ( typeof (T)); // the incoming object type 18 is the MemoryStream Stream = new new the MemoryStream (Encoding.UTF8.GetBytes (JSON)); // the memory the incoming stream Json save . 19 T obj = (T) serializer.ReadObject (Stream); // use ReadObject method deserialized into an object 20 is return obj; 21 is } 22 is the catch (Exception EX) { the throw EX;} 23 is 24 } 25 26 is /// <Summary> 27 /// convert the object Json 28 /// </ Summary> 29 /// <param name = "obj"> </ param> 30 /// <Returns > </ Returns> 31 is public String ConvertObjectToJson ( Object obj) 32 { 33 is the try 34 is { 35 String jsonStr = JsonConvert.SerializeObject (obj); // serialized object 36 return jsonStr; 37 [ } 38 is the catch(Exception ex) { throw ex; } 39 } 40 41 #endregion
NOTE: used to using Newtonsoft.Json, you need to download the installation package manager VS