1 using System;
2 using System.Collections.Generic;
3 using System.Web.Script.Serialization;
4 using System.Configuration;
5 using System.Runtime.Serialization.Json;
6 using System.Runtime.Serialization;
7 using System.IO;
8 using System.Text;
9
10
11 namespace WebApplication1
12 {
13
14 //方法一:引入System.Web.Script.Serialization命名空间使用 JavaScriptSerializer类实现简单的序列化
15 [Serializable]
16 public class Person
17 {
18
19 private int id;
20 /// <summary>
21 /// id
22 /// </summary>
23 public int Id
24 {
25 get { return id; }
26 set { id = value; }
27 }
28
29 private string name;
30 /// <summary>
31 /// 姓名
32 /// </summary>
33 public string Name
34 {
35 get { return name; }
36 set { name = value; }
37 }
38 }
39
40 //方法二:引入 System.Runtime.Serialization.Json命名空间使用 DataContractJsonSerializer类实现序列化
41 //可以使用IgnoreDataMember:指定该成员不是数据协定的一部分且没有进行序列化,DataMember:定义序列化属性参数,使用DataMember属性标记字段必须使用DataContract标记类 否则DataMember标记不起作用。
42 [DataContract]
43 public class Person1
44 {
45
46 [IgnoreDataMember]
47 public int Id { get; set; }
48
49 [DataMember(Name = "name")]
50 public string Name { get; set; }
51 [DataMember(Name = "sex")]
52 public string Sex { get; set; }
53
54 }
55
56 public partial class _Default : System.Web.UI.Page
57 {
58 string constr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
59
60 protected void Page_Load(object sender, EventArgs e)
61 {
62
63 Person p1 = new Person();
64 p1.Id = 1;
65 p1.Name = "dxw";
66 Person p2 = new Person();
67 p2.Id = 2;
68 p2.Name = "wn";
69
70 List<Person> listperson = new List<Person>();
71 listperson.Add(p1);
72 listperson.Add(p2);
73
74 JavaScriptSerializer js = new JavaScriptSerializer();
75 //json序列化
76 string s = js.Serialize(listperson);
77 Response.Write(s);
78
79
80
81 //方法二
82 Person1 p11 = new Person1();
83 p11.Id = 1;
84 p11.Name = "hello";
85 p11.Sex = "男";
86 DataContractJsonSerializer json = new DataContractJsonSerializer(p11.GetType());
87
88 string szJson = "";
89
90 //序列化
91
92 using (MemoryStream stream = new MemoryStream())
93
94 {
95
96 json.WriteObject(stream, p11);
97
98 szJson = Encoding.UTF8.GetString(stream.ToArray());
99
100 Response.Write(szJson);
101 }
102
103 //反序列化
104
105 //using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
106
107 //{
108
109 // DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
110
111 // Person1 _people = (Person1)serializer.ReadObject(ms);
112
113 //}
114 }
115
116
117
118 protected void Button1_Click(object sender, EventArgs e)
119 {
120 Response.Write(constr);
121 }
122
123
124 }