method One: Introduce System.Web.Script.Serialization namespaces to implement simple serialization using JavaScriptSerializer class Serialization class: Personnel
Copy Code code as follows:
public class personnel
{
public int Id {get; set;}
public string Name {get; set;}
}
To perform serialization deserialization:
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
Personnel personnel = new personnel ();
Personnel. Id = 1;
Personnel. Name = "small white";
JavaScriptSerializer Jsonserializer = new JavaScriptSerializer ();
Perform serialization
string R1 = Jsonserializer.serialize (Personnel);
Perform deserialization
Personnel _personnel = jsonserializer.deserialize<personnel> (r1);
}
R1 output: {"Id": 1, "Name": "Small White"}
You can use the Scriptignore property tag to not serialize public properties or public fields.
Copy Code code as follows:
public class personnel
{
[Scriptignore]
public int Id {get; set;}
public string Name {get; set;}
}
R1 Output Result: {"Name": "Small White"}
method Two: Introducing System.Runtime.Serialization.Json namespaces to implement serialization using the DataContractJsonSerializer class
Serialization class: People
Copy Code code as follows:
public class people
{
public int Id {get; set;}
public string Name {get; set;}
}
perform serialization deserialization
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
People people = new people ();
People. Id = 1;
People. Name = "small white";
DataContractJsonSerializer json = new DataContractJsonSerializer (people. GetType ());
String Szjson = "";
Serialization of
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: {"Id": 1, "Name": "Small White"}
You can use Ignoredatamember: Specify that the member is not part of a data contract and is not serialized, DataMember: Define serialization Property arguments, use the DataMember property tag field to use the DataContract tag class Otherwise, the DataMember tag does not work.
Copy Code code as follows:
[DataContract]
public class people
{
[DataMember (Name = "id")]
public int Id {get; set;}
[Ignoredatamember]
public string Name {get; set;}
}
Output result: {"id": 1}