JSON Helper Class:
A Generic Class which is Helpful to serialize & de serialize
your JSON Object.
Make sure that you have added reference for System.Runtime.Serialization in your application
1.
using System.IO;
2.
using System.Text;
3.
using System.Runtime.Serialization.Json;
4.
public class JSonHelper
5.
{
6.
public string ConvertObjectToJSon<T>(T yourObj)
7.
{
8.
DataContractJsonSerializer ser =
9.
new DataContractJsonSerializer(typeof(T));
10.
MemoryStream ms = new MemoryStream();
11.
ser.WriteObject(ms, yourObj);
12.
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
13.
ms.Close();
14.
return jsonString;
15.
}
16.
17.
public T ConvertJSonToObject<T>(string yourJsonString)
18.
{
19.
DataContractJsonSerializer
serializer =
20.
new DataContractJsonSerializer(typeof(T));
21.
MemoryStream ms =
22.
new MemoryStream(Encoding.UTF8.GetBytes(yourJsonString));
23.
T obj = (T)serializer.ReadObject(ms);
24.
return obj;
25.
}
26.
}
27.
No comments:
Post a Comment