You can use the DataContractJsonSerializer class to serialize a type instance to a JSON string and deserialize the JSON string into a type instance. DataContractJsonSerializer under the System.Runtime.Serialization.Json namespace
, the. NET Framework 3.5 is included in System.ServiceModel.Web.dll, and you need to add a reference to it;. NET Framework 4 in System.Runtime.Serialization.
Using DataContractJsonSerializer to serialize and deserialize code:
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>: JSON serialization and deserialization helper classes one by one://</summary> 12:public class Jsonhelper 13: {14: <summary>://JSON Serialization:///</summary> 17:public static string jsonserializer<t& gt; (t): {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; :} 26:27:///<summary>: JSON deserialization:///</summary> 30:public static T J Sondeserialize<t> (String jsonstring): {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 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 = "Zhang San"; 5: p.age = 28; 6:7: String jsonstring = Jsonhelper.jsonserializer<person> (p); 8: Response.Write (jsonstring); 9:}
Output Result:
{"Age": +, "Name": "Zhang San"}
Deserialization Demo:
1:protected void Page_Load (object sender, EventArgs e) 2: {3: string jsonstring = "{\" age\ ": 28,\" name\ ": \" Zhang San \ "}"; 4: Person p = jsonhelper.jsondeserialize<person> (jsonstring); 5:}
ASP. NET JSON serialization and deserialization can also use JavaScriptSerializer, in the System.Web.Script.Serializatioin namespace, reference System.Web.Extensions.dll is required. You can also use the json.net.