JSON stands for Javascript Object Notation and this is the new lightweight (then XML) standart for transferring data from one point to another over the network. Here you can find a sample web page codebehind to see usage in C#.
1 namespace Prototype
2 {
3 public partial class Json : System.Web.UI.Page
4 {
5 protected void Page_Load(object sender, EventArgs e)
6 {
7 //create instance of the object
8 SampleObject sampleObject = new SampleObject();
9
10 //Json Serialize
11 string json = Functions.ToJson<SampleObject>(sampleObject);
12
13 Response.Write(string.Format("Json result: {0}<br/>",Server.HtmlEncode(json)));
14
15 SampleObject deserializedSampleObject = Functions.FromJson<SampleObject>(json);//Json Deserialize
16 Response.Write(string.Format("Object Result: {0}<br/>", deserializedSampleObject.ToString()));
17
18 }
19 }
20
21 [Serializable]
22 public class SampleObject
23 {
24 public int Id { get; set; }
25 public string Name { get; set; }
26 public string Surname { get; set; }
27 public string EMail { get; set; }
28
29 public SampleObject()
30 {
31 this.Id = 2345;
32 this.Name = "Ozan K.";
33 this.Surname = "BAYRAM";
34 this.EMail = "xyz@abc.com";
35 }
36
37 public override string ToString()
38 {
39 return string.Format("{0} {1}", Name, Surname);
40 }
41 }
42 }
Static methods in 'Functions' class
1 /// <summary>
2 /// Serializes to Json string
3 /// Class must be serializable
4 /// </summary>
5 /// <typeparam name="T"></typeparam>
6 /// <param name="ObjectToSerialize"></param>
7 /// <returns>json string</returns>
8 public static string ToJson<T>(object ObjectToSerialize)
9 {
10 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
11 MemoryStream ms = new MemoryStream();
12 ser.WriteObject(ms, ObjectToSerialize);
13
14 string json = Encoding.Default.GetString(ms.ToArray());
15 ms.Close();
16
17 return json;
18
19 }
20
21 /// <summary>
22 /// Deserializes json string to object
23 /// </summary>
24 /// <typeparam name="T"></typeparam>
25 /// <param name="JsonString"></param>
26 /// <returns></returns>
27 public static T FromJson<T>(string JsonString)
28 {
29 MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonString));
30
31 DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
32 T returnObject = (T)ser.ReadObject(ms);
33 ms.Close();
34
35 return returnObject;
36 }
Happy codings...
1 kişi tarafından 2.0 olarak değerlendirildi
- Currently 2/5 Stars.
- 1
- 2
- 3
- 4
- 5