The following is a detailed analysis of JSON serialization and deserialization. If you need it, refer to Method 1: Introduce System. web. script. the Serialization namespace uses the JavaScriptSerializer class to implement a simple Serialization class: Personnel
public class Personnel { public int Id { get; set; } public string Name { get; set; } }
Execute serialization deserialization:
Protected void Page_Load (object sender, EventArgs e) {Personnel personnel = new Personnel (); personnel. id = 1; personnel. name = ""; JavaScriptSerializer jsonSerializer = new JavaScriptSerializer (); // execute serialized string r1 = jsonSerializer. serialize (personnel); // execute deserialization of Personnel _ Personnel = jsonSerializer. deserialize
(R1 );}
R1 output result: {"Id": 1, "Name": ""}
You can use the ScriptIgnore attribute to mark public or public fields that are not serialized.
public class Personnel { [ScriptIgnore] public int Id { get; set; } public string Name { get; set; } }
R1 output result: {"Name": ""}
Method 2: introduce the System. Runtime. Serialization. Json namespace and use the DataContractJsonSerializer class for Serialization.
Serialization class: People
public class People { public int Id { get; set; } public string Name { get; set; } }
Execute serialization deserialization
Protected void Page_Load (object sender, EventArgs e) {People people = new People (); people. id = 1; people. name = ""; DataContractJsonSerializer json = new DataContractJsonSerializer (people. getType (); string szJson = ""; // serialize using (MemoryStream stream = new MemoryStream () {json. writeObject (stream, people); szJson = Encoding. UTF8.GetString (stream. toArray ();} // deserialization of using (MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (szJson) {DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (People); People _ people = (People) serializer. readObject (MS );}}
SzJson output result: {"Id": 1, "Name": ""}
You can use IgnoreDataMember to specify that the member is not part of the Data Protocol and is not serialized. DataMember: defines the serialization attribute parameters. Fields marked with the DataMember attribute must use the DataContract tag class. Otherwise, the DataMember tag does not work.
[DataContract] public class People { [DataMember(Name = "id")] public int Id { get; set; } [IgnoreDataMember] public string Name { get; set; } }
Output result: {"id": 1}
For more articles about JSON serialization and deserialization, refer to PHP Chinese network!