Method 1: introduce the System. Web. Script. Serialization namespace and use the JavaScriptSerializer class for simple Serialization.Serialization class: Personnel
Copy codeThe Code is as follows:
Public class Personnel
{
Public int Id {get; set ;}
Public string Name {get; set ;}
}
Execute serialization deserialization:
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
Personnel personnel = new Personnel ();
Personnel. Id = 1;
Personnel. Name = "";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer ();
// Execute serialization
String r1 = jsonSerializer. Serialize (personnel );
// Execute deserialization
Personnel _ Personnel = jsonSerializer. Deserialize <Personnel> (r1 );
}
R1 output result: {"Id": 1, "Name": ""}
You can use the ScriptIgnore attribute to mark public or public fields that are not serialized.
Copy codeThe Code is as follows:
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
Copy codeThe Code is as follows:
Public class People
{
Public int Id {get; set ;}
Public string Name {get; set ;}
}
Execute serialization deserialization
Copy codeThe Code is as follows:
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 = "";
// Serialization
Using (MemoryStream stream = new MemoryStream ())
{
Json. WriteObject (stream, people );
SzJson = Encoding. UTF8.GetString (stream. ToArray ());
}
// Deserialization
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.
Copy codeThe Code is as follows:
[DataContract]
Public class People
{
[DataMember (Name = "id")]
Public int Id {get; set ;}
[IgnoreDataMember]
Public string Name {get; set ;}
}
Output result: {"id": 1}