$.toJSON的用法或把数组转换成json类型

£可爱£侵袭症+ 提交于 2020-02-04 04:13:52

1. html页面全部代码

<html>
<head>
    <title></title>
    <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="../../Scripts/JqueryJson.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#json").click(function () {

             //数组里的字段的命名和类型要和一般处理程序里定义的类里的变量要一样

             //否则会出问题
                var postdata = new Array();
                postdata[1] = { id: 1, number: "yes" };
                postdata[2] = { id: 2, number: "no" };

 

                var postData = $.toJSON(postdata);  //把数组转换成json字符串

                //将json字符串反序列化,这个只是测试一下数组是否转换成json字符串

                var content = $.parseJSON(postData);
                $.each(content, function () {
                    alert(this.number);
                });

                //post提交并处理

                $.post("json.ashx", { "array": postData }, function (data, status) {
                    if (status == "success") {
                        alert(data);
                    }
                });

            });
        })
    </script>
</head>
<body>
<input type="button" value="json" id="json"/>
</body>
</html>

2.json.ashx页面全部代码

<%@ WebHandler Language="C#" class="json" %>

using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;

public class json : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
               
        //接受出过来的值 

        string sun = context.Request["array"].ToString();

        //实例化JavaScriptSerializer对象
        JavaScriptSerializer jss = new JavaScriptSerializer();
        List<array> a = new List<array>();

        //把json转换其他list<array>类型
        a = jss.Deserialize(sun, typeof(List<array>)) as List<array>;
        string meg=null;
        foreach (var item in a)
        {
            meg += item.number;
        }
        context.Response.Write(meg);
    }

    public class array
    {
        public int id { get; set; }
        public string number { get; set; }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!