苏州北大青鸟|电脑人才培训中心『官方网站』

高中生毕业了做什么?高中生学什么好 苏州北大青鸟、苏州北大青鸟学费、苏州北大青鸟地址
ACCP7.0培训-入手最快 JAVA培训—收入最高 .NET培训—就业面最宽 网络营销培训—需求量最大
高中毕业学什么好 大学生找不到工作怎么办 学什么技术有前途(好转行) 初中(中专)毕业学什么好
当前位置: 主页 > 青鸟百科 >

.NET下JSON程序的常用操作技巧

时间:2013-08-22 17:06来源:未知 作者:admin 点击:

.NET下JSON程序的常用操作技巧有哪些?现在,北大青鸟.NET老师做出以下技巧总结:       
       1.JSON的序列化和反序列化

Newtonsoft.Json dll 下载地址http://json.codeplex.com/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
  
namespace PlayJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            List<StuInfo> list = new List<StuInfo>() { newStuInfo{StuName="张三",StuSex="男",StuAge=11},
                                                       newStuInfo{StuName="李四",StuSex="男",StuAge=32},
                                                       newStuInfo{StuName="王翠花",StuSex="女",StuAge=64}
                                                      };
            string jsonStr = Javas criptConvert.SerializeObject(list);  //将对象转换成json存储
            Console.WriteLine("JSON字符串"+jsonStr);
            Console.ReadLine();
  
            List<StuInfo> newList = new List<StuInfo>();
  
           newList = (List<StuInfo>)Javas criptConvert.DeserializeObject(jsonStr,typeof(List<StuInfo>));  //反序列化
  
            //StuInfo s = new StuInfo() { StuName = "阿龙", StuSex = "男", StuAge = 33 };
  
            //string sigleJSON = Javas criptConvert.SerializeObject(s);
  
           //StuInfo newS = (StuInfo)Javas criptConvert.DeserializeObject(sigleJSON);
           //Console.WriteLine("姓名:" + newS.StuName + "---性别:" + newS.StuSex + "--年龄:" + newS.StuAge + "nn");
  
  
           foreach (StuInfo item in newList)
           {
               Console.WriteLine("姓名:" + item.StuName + "---性别:" + item.StuSex + "--年龄:" + item.StuAge + "nn");
           }
            Console.ReadLine();
        }
    }
    public class StuInfo
    {
        public string StuName { set; get; }
        public string StuSex { set; get; }
        public int StuAge { set; get; }
    }
}
?

  2.在web中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {
  
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
  
            List<StuInfo> list = new List<StuInfo>() { newStuInfo{StuName="张三",StuSex="男",StuAge=11},
                                                       newStuInfo{StuName="李四",StuSex="男",StuAge=32},
                                                       newStuInfo{StuName="王翠花",StuSex="女",StuAge=64}
                                                      };
            string jsonStr = Javas criptConvert.SerializeObject(list);
  
            context.Response.Write(jsonStr);
  
            context.Response.End();
        }
  
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    public class StuInfo
    {
        public string StuName { set; get; }
        public string StuSex { set; get; }
        public int StuAge { set; get; }
    }

  前台页面上的调用:这里采用jquery 的ajax请求

1
<head runat="server"><title>JSON</title><s cript src="s cripts/jquery-1.4.1.min.js" type="text/javas cript"></s cript><s cript type="text/javas cript">        $(function () {            $("#btnOK").click(function () {                $.ajax({                    type: "JSON",                    url:"Handler1.ashx",                    data:null,                    success: function (msg) {                        var con="";                        for(var i =0; i < msg.length; i++) {                            con +="姓名:"+ msg[i].StuName +"--性别:"+ msg[i].StuSex +"--"+"--年龄:"+ msg[i].StuAge+"<br/>";                        }                        $("#divContent").html("长度:"+ msg.length +"--具体内容:<br/>"+ con);                    }                });            });        });    </s cript></head><body><form id="form1" runat="server"><div><input type="button" id="btnOK" value="点我获得JSON数据"/><div id="divContent"></div></div></form></body>

现在经常会用到json,因此经常会需要对其进行序列化和反序列化。,.NET Framewok 3.5也提供了JSON对象序列化和反序列化的类,这就是System.Runtime.Serialization.Json 命名空间下的 DataContractJsonSerializer 类。利用这个类,可以实现JSON对象的序列化和反序列化。

现在我提供一个类JSON对象序列化和反序列化的类供参考用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/// <summary>
    /// JSON帮助类。用于将对象转换为Json格式的字符串,或者将Json的字符串转化为对象。
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 将对象转化为Json字符串
        /// </summary>
        /// <typeparam name="T">源类型</typeparam>
        /// <param name="obj">源类型实例</param>
        /// <returns>Json字符串</returns>
        public static string GetJsonFromObj<T>(T obj)
        {
            DataContractJsonSerializer jsonSerializer = newDataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                jsonSerializer.WriteObject(ms, obj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
  
        /// <summary>
        /// 将Json字符串转化为对象
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="strJson">Json字符串</param>
        /// <returns>目标类型的一个实例</returns>
        public static T GetObjFromJson<T>(string strJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = newMemoryStream(Encoding.UTF8.GetBytes(strJson)))
            {
                DataContractJsonSerializer jsonSerializer = newDataContractJsonSerializer(obj.GetType());
                return (T)jsonSerializer.ReadObject(ms);
            }
        }
  
        /// <summary>
        /// 将DataTable转换为JSON字符串
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <returns>JSON字符串</returns>
        public static string GetJsonFromDataTable(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append(""TableInfo":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" """ + dt.Rows[i][j].ToString() + "",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" """ + dt.Rows[i][j].ToString() + """);
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }
  
        /// <summary>
        /// 将对象转化为Json字符串
        /// </summary>
        /// <param name="obj">源对象</param>
        /// <returns>json数据</returns>
        public static string ObjToJson(this object obj)
        {
            Javas criptSerializer serialize = new Javas criptSerializer();
            return serialize.Serialize(obj);
        }
  
        /// <summary>
        /// 将Json字符串转化为对象
        /// </summary>
        /// <param name="strJson">Json字符串</param>
        /// <returns>目标对象</returns>
        public static T JsonToObj<T>(string strJson)
        {
            Javas criptSerializer serialize = new Javas criptSerializer();
            return serialize.Deserialize<T>(strJson);
        }
  
        /// <summary>
        /// 将对象转化为Json字符串(控制深度 )
        /// </summary>
        /// <param name="obj">源对象</param>
        /// <param name="recursionDepth">深度</param>
        /// <returns>json数据</returns>
        public static string ObjToJson(this object obj, intrecursionDepth)
        {
            Javas criptSerializer serialize = new Javas criptSerializer();
            serialize.RecursionLimit = recursionDepth;
            return serialize.Serialize(obj);
        }
  
        /// <summary>
        /// 将Json字符串转化为对象(控制深度 )
        /// </summary>
        /// <param name="strJson">Json字符串</param>
        /// <param name="recursionDepth">深度</param>
        /// <returns>目标对象</returns>
        public static T JsonToObj<T>(string strJson, intrecursionDepth)
        {
            Javas criptSerializer serialize = new Javas criptSerializer();
            serialize.RecursionLimit = recursionDepth;
            return serialize.Deserialize<T>(strJson);
        }
  
        /// <summary>
        /// 将DataTable转换为JSON字符串
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns>json数据</returns>
        public static string DataTableToJson(DataTable dt)
        {
            Dictionary<string, object> dic = newDictionary<string, object>();
  
            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = newDictionary<string, object>();
  
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                dic.Add(index.ToString(), result);
                index++;
            }
            return ObjToJson(dic);
        }
    }

  使用如下:

1
2
3
4
5
6
public partial class WebForm1 : System.Web.UI.Page    {       protected void Page_Load(object sender, EventArgs e)        {        }        protected void Button1_Click(object sender, EventArgs e)        {            //反序列化成对象                 String strJson = "{"Name":"Test123","Url":"http://www.126.com/"}";            Person p1 = JsonHelper.GetObjFromJson<Person>(strJson);            Response.Write("<li>" + p1.Name + " " + p1.Url);            Person p2 = JsonHelper.JsonToObj<Person>(strJson);            Response.Write("<li>" + p2.Name + " " + p2.Url);        }        protected void Button2_Click(object sender, EventArgs e)        {            //对象的序列化             String JSONString = string.Empty;            Person p1 = new Person();            p1.Name = "Test123'"nrt";            p1.Url = "http://www.126.com/";            JSONString = JsonHelper.GetJsonFromObj<Person>(p1);            Response.Write("<li>" + JSONString);            JSONString = JsonHelper.ObjToJson(p1);            Response.Write("<li>" + JSONString);        }    }    /// <summary>     /// 类对象需要标记为DataContractAttribute     /// </summary>     [DataContractAttribute]    class Person    {        //成员需要标记为 DataMember         [DataMember]        public string Name { set; get; }        [DataMember]        public string Url { set; get; }    }
补充:
在C#中可以对JSON进行序列化与反序列化,十分的方便。代码如下:
首先引入命名空间:using System.Web.s cript.Serialization;
再定义一个类,如下:
publicclass jsonClass    {        publicstring id;        publicstring name;        publicstring pId;        publicstring isParent;        publicstring open;        publicstring senable;        publicstring CHECKED;        publicstring chkDisabled;    }

将一个JSON字符串转换成jsonClass类实例,如下:

1
Javas criptSerializer serializer = new Javas criptSerializer();                    List<jsonClass> jsonClassList = serializer.Deserialize<List<jsonClass>>(jsonString);

将List<jsonClass>转换成json

1
string resultString = serializer.Serialize(jsonClassList);
 
北大青鸟苏州电脑人才)


(原文标题:.NET下JSON程序的常用操作技巧

(责任编辑:苏州北大青鸟



相关新闻

更多
分享按钮
------分隔线----------------------------
招生专题