Method 1: introduce the System. Web. Script. Serialization namespace and use the JavaScriptSerializer class for simple Serialization.
Serialization class: Personnel
Publicclass Personnel
{
Publicint Id {get; set ;}
Publicstring Name {get; set ;}
}
Execute serialization deserialization:
Code
Protectedvoid Page_Load (object sender, EventArgs e)
{
Personnel personnel = new Personnel ();
Personnel. Id = 1;
Personnel. Name = "";
JavaScriptSerializerjsonSerializer = 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.
Publicclass Personnel
{
[ScriptIgnore]
Publicint Id {get; set ;}
Publicstring 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
Publicclass People
{
Publicint Id {get; set ;}
Publicstring Name {get; set ;}
}
Execute serialization deserialization www.2cto.com
Code
Protectedvoid Page_Load (object sender, EventArgs e)
{
People people = new People ();
People. Id = 1;
People. Name = "";
DataContractJsonSerializerjson = 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 = newMemoryStream (Encoding. UTF8.GetBytes (szJson )))
{
DataContractJsonSerializer serializer = newDataContractJsonSerializer (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.
Code
[DataContract]
Publicclass People
{
[DataMember (Name = "id")]
Publicint Id {get; set ;}
[IgnoreDataMember]
Publicstring Name {get; set ;}
}
Output result: {"id": 1}
From Zhang Yi ☆. Net★Java software alliance