jquery - 将 json 数组发送到 ashx 处理程序

标签 jquery asp.net json ashx

我有这段代码,当我执行它时,它一直显示相同的错误:无效的 JSON 原语:标题。

客户端:

        var title = new Array();

        ...

        for (var i = 0; i < names.length; ++i) {
            title[i] = '{ "titulo' + i + ':"' + names[i] + '"}';
        }

        $("#gif").show();

        $.ajax({
            async: true,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: "POST",
            data: { titles: title },
            url: "../handlers/saveUpload.ashx",
            success: function (msg) {                    
                $("#gif").hide();
            }
        });

服务器端:

        context.Response.ContentType = "application/json";
        var data = context.Request;
        var sr = new StreamReader(data.InputStream);
        var stream = sr.ReadToEnd();

        var javaScriptSerializer = new JavaScriptSerializer();

        var arrayOfStrings = javaScriptSerializer.Deserialize<string[]>(stream);

        foreach (var item in arrayOfStrings)
        {
            context.Response.Write(item);
        }

问候

最佳答案

在这篇文章中解决:convert array to json and receive in ashx handler

string[] is not a valid generic type for that operation; string doesn't have a parameterless constructor so when the serialiser tries to new one up, it fails. Besides, you already have a string from sr.ReadToEnd() so you're not really deserialising, it's more like you are asking it to parse and split the string for you, which it can't do.

JavaScriptSerializer 非常无情,说实话,当我尝试反序列化这样的数组时,我总是会抓狂……最好在服务器端定义一个 DTO 类来处理映射:

 [Serializable]
 public class Titles
 {
    public List<Title> TheTitles { get; set; } 
 }

 [Serializable]
 public class Title
 {
    public string title { get; set; }
 }

现在你的处理程序看起来像这样:

 public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "application/json";
                var data = context.Request;
                var sr = new StreamReader(data.InputStream);
                var stream = sr.ReadToEnd();    
                var javaScriptSerializer = new JavaScriptSerializer();
                var PostedData = javaScriptSerializer.Deserialize<Titles>(stream);    
                foreach (var item in PostedData.TheTitles )
                {
                   //this will write SteveJohnAndrew as expected in the response 
                   //(check the console!)
                   context.Response.Write(item.title);
                }
            }
            catch (Exception msg) { context.Response.Write(msg.Message); }
        }

你的 AJAX 是这样的:

 function upload() 
        {
           //example data
            var Titles = [
                {'title':'Steve'}, {'title':'John'}, {'title':'Andrew'}
            ];    
            var myJSON = JSON.stringify({ TheTitles: Titles });    
            console.log(myJSON);    
            $.ajax({
                async: true,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                type: "POST",
                data: myJSON,
                url: "jsonhandler.ashx",
                success: function (msg) {
                    console.log(msg);
                }     
            });
        }

请注意 DTO 类的定义如何与 JSON 对象属性的定义完全匹配,如果不匹配,则反序列化将不起作用。

希望有帮助。

关于jquery - 将 json 数组发送到 ashx 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19809791/

相关文章:

javascript - 使用 .html() 隐藏 <div> 中的内容而不隐藏内部 <div>

javascript - 使用 javascript 检测页面卸载

jquery 特定图像的图像点击事件

javascript - 如何在同一页面上创建多个谷歌地图(不是标记)?

json - Node.js GET 请求有时会收到 HTML 文档而不是 JSON 并崩溃

javascript - jQuery html() 表现真的很慢

ASP.NET HyperLink - 设置图像的 Alt 标签

asp.net - 将网站/页面嵌入 Silverlight

asp.net - 使用linq获取网页中某种类型的Web控件列表

json - 使用 jsonschema 和 robotsframework 验证 json