使用C#中JavaScriptSerializer类将对象转换为Json格式数据

将对象转换为json格式字符串:

private JavaScriptSerializer serializer = new JavaScriptSerializer();
protected void Page_Load(object sender, EventArgs e)
{
    Books book = new Books();
    book.BookId = 1;
    book.BookName = "书籍1";
    book.BookCount = 999;
    string jsonStr = serializer.Serialize(book);
    //jsonStr结果:{"BookId":1,"BookName":"书籍1","BookCount":999}
}

 

Aspx前台页面,jQuery发送Ajax请求:

function loadrecomticket() {
    jQuery.post(
                    "/Ajax/TicketBoxAsx.ashx",
                    {
                        ajaxMethod: "getrecomticket",
                        random: Math.random()
                    },
                    function(data) {
                        if (data.result) {   //面向对象思想:把返回的对象data,直接data.result,类似对象.属性名
                            $("#M1_LeftCount").html(data.list[0].leftCount);
                            $("#M1_GetCount").html(data.list[0].GetCount);
                            $("#M_UsedCount").html(data.list[0].UsedCount);

                            $("#M2_LeftCount").html(data.list[1].LeftCount);
                            $("#M2_GetCount").html(data.list[1].GetCount);
                            $("#M2_UsedCount0").html(data.list[1].UsedCount);

                            $("#M3_LeftCount").html(data.list[2].LeftCount);
                            $("#M3_Getcount").html(data.list[2].GetCount);
                            $("#M3_UsedCount").html(data.list[2].UsedCount);
                        }
                    },
                "json");
}

 

一般处理程序接收参数并处理请求,返回json格式数据:

namespace Test.Ajax
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class TicketBoxAsx : BaseCommon, IHttpHandler
    {
        private Business.RecomTicket recomTicket = new Business.RecomTicket();

        public void ProcessRequest(HttpContext context)
        {
            if (this.UserId > 0)
            {
                if (!string.IsNullOrEmpty(context.Request["ajaxMethod"]))
                {
                    context.Response.ContentType = "text/plain";
                    string ajaxMethod = context.Request["ajaxMethod"].ToLower();
                    switch (ajaxMethod)
                    {
                        case "getrecomticket":
                            GetRecomTicket(context);
                            break;
                    }
                }
            }
            else
            {
                Utility.ResponseWriteEnd(this.ProcessResponseText("({result:0,error:'请先登录!'})"));
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        
        private void GetRecomTicket(HttpContext context)
        {
            TicketBoxInfo M1 = new TicketBoxInfo(); //创建3个对象
            TicketBoxInfo M2 = new TicketBoxInfo();
            TicketBoxInfo M3 = new TicketBoxInfo();
            BusinessResult<RecomTicketInfo> info = this.recomTicket.GetUserVoteTicket(this.UserId);
            if (info.IsSuccess)
            {
                RecomTicketInfo recomTicketInfo = info.ReturnObject;
//为3个对象属性赋值 M1.leftCount
= Math.Max(recomTicketInfo.MaxRecomTicket - recomTicketInfo.TodayUsedRecomTicket, 0);
M1.MGetCount = recomTicketInfo.MaxRecomTicket;
M1.UsedCount = recomTicketInfo.TodayUsedRecomTicket;
M2.leftCount
= Math.Max(recomTicketInfo.MaxRecomTicket - recomTicketInfo.TodayMMUsedRecomTicket, 0);
M2.MGetCount = recomTicketInfo.MaxRecomTicket;
M2.UsedCount = recomTicketInfo.TodayMMUsedRecomTicket;
M3.leftCount
= Math.Max(recomTicketInfo.MaxRecomTicket - recomTicketInfo.TodayWXUsedRecomTicket, 0);
M3.MGetCount = recomTicketInfo.MaxRecomTicket;
M3.UsedCount = recomTicketInfo.TodayWXUsedRecomTicket; } JavaScriptSerializer js = new JavaScriptSerializer(); //命名空间:using System.Web.Script.Serialization; Utility.ResponseWriteEnd(this.ProcessResponseText("({result:1, list:[" + js.Serialize(M1) + "," + js.Serialize(M2) + "," + js.Serialize(M3) + "]})")); } } }

 

备注:

JSON格式:

普通形式:
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }

数组形式:
1.单元素:
{
"people": [
                { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
                { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},
                { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
            ]
}

2.多元素:
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }


格式应用
掌握了 JSON 格式之后,在 JavaScript 中使用它就很简单了。JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON 数据不需要任何特殊的 API 或工具包。
赋值给变量
例如,可以创建一个新的 JavaScript 变量,然后将 JSON 格式的数据字符串直接赋值给它:

var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
数据访问: people.authors[
1].genre // Value is "fantasy" 下标从0开始 people.musicians[3].lastName // Undefined. This refers to the fourth entry, and there isn't one people.programmers[2].firstName // Value is "Elliotte"

 

百度百科JSON介绍>>

博文推荐:C# JSON字符串序列化与反序列化

格式应用

掌握了 JSON 格式之后,在 JavaScript 中使用它就很简单了。JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON 数据不需要任何特殊的 API 或工具包。

赋值给变量

例如,可以创建一个新的 JavaScript 变量,然后将 JSON 格式的数据字符串直接赋值给它:
[3]
1
2
3
4
5
6
7
8
9
10
11
12
13
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
posted @ 2013-11-15 16:44  IT浪潮之巅  阅读(2730)  评论(0编辑  收藏  举报
   友情链接: 淘宝优惠券