You can use the datacontractjsonserializer class to serialize a type instance to a JSON string and deserialize the JSON string to a type instance. Datacontractjsonserializer Is In The namespace of system. runtime. serialization. JSON.
. NET Framework 3.5 is included in system. servicemodel. Web. dll. You need to add a reference to it;. NET Framework 4 is in system. runtime. serialization.
Using datacontractjsonserializer for serialization and deserializationCode:
1: using system;
2: using system. Collections. Generic;
3: using system. LINQ;
4: using system. Web;
5: using system. runtime. serialization. JSON;
6: using system. IO;
7: using system. text;
8:
9: // <summary>
10: // JSON serialization and deserialization helper class
11: // </Summary>
12: public class jsonhelper
13 :{
14: // <summary>
15: // JSON serialization
16: // </Summary>
17: public static string jsonserializer <t> (T)
18 :{
19: datacontractjsonserializer SER = new datacontractjsonserializer (typeof (t ));
20: memorystream MS = new memorystream ();
21: Ser. writeobject (MS, t );
22: String jsonstring = encoding. utf8.getstring (Ms. toarray ());
23: Ms. Close ();
24: Return jsonstring;
25 :}
26:
27: // <summary>
28: // JSON deserialization
29: // </Summary>
30: public static t jsondeserialize <t> (string jsonstring)
31 :{
32: datacontractjsonserializer SER = new datacontractjsonserializer (typeof (t ));
33: memorystream MS = new memorystream (encoding. utf8.getbytes (jsonstring ));
34: t obj = (t) SER. readobject (MS );
35: Return OBJ;
36 :}
37 :}
Serialization Demo:
Simple Object person:
1: Public class person
2 :{
3: Public string name {Get; set ;}
4: Public int age {Get; set ;}
5 :}
Serialized as a JSON string:
1: protected void page_load (Object sender, eventargs E)
2 :{
3: person P = new person ();
4: P. Name = "James ";
5: P. Age = 28;
6:
7: String jsonstring = jsonhelper. jsonserializer <person> (P );
8: Response. Write (jsonstring );
9 :}
Output result:
{"Age": 28, "name": "Zhang San "}
Deserialization Demo:
1: protected void page_load (Object sender, eventargs E)
2 :{
3: String jsonstring = "{\" Age \ ": 28, \" Name \ ": \" James \"}";
4: person P = jsonhelper. jsondeserialize <person> (jsonstring );
5 :}
ASP. you can also use javascriptserializer for JSON serialization and deserialization in. net. web. script. in the serializatioin namespace, system must be referenced. web. extensions. DLL. you can also use JSON. net.