method One: Introduce a System.Web.Script.Serialization namespace using the JavaScriptSerializer class for simple serialization
Serialization class: Personnel
public class personnel
{
public int Id {get; set;}
public string Name {get; set;}
}
To perform serialization deserialization:
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);
Performing deserialization
Personnel _personnel = jsonserializer.deserialize<personnel> (r1);
}
R1 output: {"Id": 1, "Name": "Small White"}
You can use the Scriptignore property to mark non-serialized public properties or public fields.
public class personnel
{
[Scriptignore]
public int Id {get; set;}
public string Name {get; set;}
}
R1 output: {"Name": "Small White"}
Method Two: introduce System.Runtime.Serialization.Json namespaces using the DataContractJsonSerializer class for serialization
Serialization class: People
public class people
{
public int Id {get; set;}
public string Name {get; set;}
}
Performing serialization deserialization
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: to specify that the member is not part of the data contract and is not serialized, DataMember: Defining a serialization attribute parameter, using the DataMember property tag field 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: {"id": 1}
Introduction to C # Implementation of JSON serialization and deserialization