/// <summary> /// 员工信息实体 /// </summary> [DataContract(Namespace = "http://micromouse.cnblogs.com")] public class EmployeeEntity { /// <summary> /// 员工ID /// </summary> [DataMember(Order = 0)] public string EmployeeID { get; set; } /// <summary> /// 员工姓名 /// </summary> [DataMember(Order = 1)] public string EmployeeName { get; set; } /// <summary> /// 出生日期 /// </summary> [DataMember(Order = 2)] public DateTime BirthdayDate { get; set; } /// <summary> /// 地址信息 /// </summary> [DataMember(Order = 3)] public AddressinfoEntity AddressInfo { get; set; } } /// <summary> /// 地址信息实体 /// </summary> [DataContract(Namespace = "http://micromouse.cnblogs.com")] public class AddressinfoEntity { /// <summary> /// 街道名称 /// </summary> [DataMember(Order = 0)] public string StreetName { get; set; } /// <summary> /// 门牌号 /// </summary> [DataMember(Order = 1)] public string HouseNumber { get; set; } }
/// <summary> /// 序列化JSON(将对象序列化为JSON字符串) /// </summary> protected void btnSerializeJSON_Click(object sender, EventArgs e) { var employeeEntity = new EmployeeEntity() { EmployeeID = Guid.NewGuid().ToString(""), EmployeeName = "张三", BirthdayDate = DateTime.Now, AddressInfo = new AddressinfoEntity() { StreetName = "一环路北三段55号", HouseNumber = "55" } }; var serializer = new DataContractJsonSerializer(typeof(EmployeeEntity)); using (var stream = new MemoryStream()) { serializer.WriteObject(stream, employeeEntity); byte[] dataBytes = new byte[stream.Length]; stream.Position = 0; stream.Read(dataBytes, 0, dataBytes.Length); txtJSON.Text = Encoding.UTF8.GetString(dataBytes); } } /// <summary> /// 反序列化JSON(将JSON字符串反序列化为对象) /// </summary> protected void btnDeserializeJSON_Click(object sender, EventArgs e) { var serializer = new DataContractJsonSerializer(typeof(EmployeeEntity)); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(txtJSON.Text))) { EmployeeEntity employeeEntity = serializer.ReadObject(stream) as EmployeeEntity; txtDeJSON.Text = string.Format("employeename=[{0}]\r\n", employeeEntity.EmployeeName); txtDeJSON.Text += string.Format("birthdaydate=[{0}]\r\n", employeeEntity.BirthdayDate); txtDeJSON.Text += string.Format("streetname=[{0}]", employeeEntity.AddressInfo.StreetName); } }
序列化后结果如下:
{ "EmployeeID":"abfc39fe-e988-4d01-b70c-1b07caa1bec0", "EmployeeName":"张三", "BirthdayDate":"\/Date(1278049399906+0800)\/", "AddressInfo":{ "StreetName":"一环路北三段55号", "HouseNumber":"55" } }
反序列化后结果如下:
employeename=[张三]
birthdaydate=[2010/7/2 13:43:19]
streetname=[一环路北三段55号]