Home > Article > Web Front-end > A brief analysis of JSON serialization and deserialization
Method 1: Introduce the System.Web.Script.Serialization namespace and use the JavaScriptSerializer class to implement simple serialization. Serialization class: Personnel
public class Personnel { public int Id { get; set; } public string Name { get; set; } }
Perform serialization and deserialization:
protected void Page_Load(object sender, EventArgs e) { Personnel personnel = new Personnel(); personnel.Id = 1; personnel.Name = "小白"; JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //执行序列化 string r1 = jsonSerializer.Serialize(personnel); //执行反序列化 Personnel _Personnel = jsonSerializer.Deserialize<Personnel>(r1); }
r1 output result: {"Id":1,"Name":"小白"}
You can use the ScriptIgnore attribute to mark public properties or public fields not to be 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 to implement serialization
Serialization class: People
public class People { public int Id { get; set; } public string Name { get; set; } }
Perform serialization and 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 = ""; //序列化 using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, people); szJson = Encoding.UTF8.GetString(stream.ToArray()); } //反序列化 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 contract and is not serialized. DataMember: defines the serialization attribute parameters. Use the DataMember attribute to mark fields. You must use DataContract to mark the class otherwise DataMember Tags don't 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 on JSON serialization and deserialization, please pay attention to the PHP Chinese website!