There are two main ways in which C # handles JSON files:
(1) using the JavaScriptSerializer class , you need to introduce a System.Web.Extension library and add the following two references:
Using System.Web;
Using System.Web.Script.Serialization;
The main code is as follows:
Public classData { Public intId {Get;Set; } //[Scriptignore] Public stringName {Get;Set; } Public stringGetName () {returnId.tostring () +Name; } } Public classJsonpaserweb {//Object->json Public stringSerialize (Data obj) {javascriptserializer Jsonserializer=NewJavaScriptSerializer (); stringJSON =jsonserializer.serialize (obj); returnJSON; } //Json->object PublicData Deserialize (stringJSON) {JavaScriptSerializer Jsonserializer=NewJavaScriptSerializer (); //Performing deserializationData obj = jsonserializer.deserialize<data>(JSON); returnobj; } }
You can use the [Scriptignore] tag to make a variable not participate in serialization.
(2) using the DataContractJsonSerializer class , you need to introduce the System.Runtime.Serialization library and add the following references:
Using System.Runtime.Serialization;
Using System.Runtime.Serialization.Json;
The sample code looks like this:
[DataContract] Public classData {[DataMember (Name="ID", Order =0)] Public intId; [DataMember (Name="name", Order =1)] Public stringName; [DataMember (Name=" Child", Order =2)] PublicChild child =NewChild (); [DataMember (Name="List", Order =3)] Publiclist<int> Ids =Newlist<int>(); [DataMember (Name="Dictionary", Order =4)] Publicdictionary<int, child> dic =Newdictionary<int, child>(); [Ignoredatamember] Public stringDescription ="This is a JSON data class"; } Public classChild { Public floatAge ; Public stringFullName; } classJsonparserruntime {//Object->json Public stringSerialize (Data obj) {datacontractjsonserializer Jsonserializer=NewDataContractJsonSerializer (obj. GetType ()); stringJSON =""; using(MemoryStream stream =NewMemoryStream ()) {Jsonserializer.writeobject (stream, obj); JSON=Encoding.UTF8.GetString (stream. ToArray ()); } returnJSON; } //Json->object PublicData Deserialize (stringJSON) {Data obj=NULL; using(MemoryStream ms =NewMemoryStream (Encoding.UTF8.GetBytes (JSON))) {DataContractJsonSerializer Jsonserializer=NewDataContractJsonSerializer (typeof(Data)); Obj=(Data) Jsonserializer.readobject (MS); } returnobj; } }
Classes marked with [DataContract] can use both [DataMember (Name = "id", Order = 0)] Tokens to handle variables, or you can use the [Ignoredatamember] tag to make a variable not participate in serialization.
C # Read and write JSON