将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(stream); foreach (var item in arrayOfStrings) { context.Response.Write(item); } 

问候

解决了这篇文章: 将数组转换为json并在ashx处理程序中接收

string []不是该操作的有效generics类型; string没有无参数构造函数,因此当序列化程序尝试新的构造函数时,它会失败。 此外,你已经有一个来自sr.ReadToEnd()的字符串,所以你不是真的反序列化,它更像是你要求它解析并拆分你的字符串,这是不能做到的。

JavaScriptSerializer是非常无情的,说实话,我总是在试图反序列化这样的数组时总是撕掉我的头发…你最好在服务器端定义一个DTO类来处理映射:

  [Serializable] public class Titles { public List 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(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对象属性的定义完全匹配,如果没有,则反序列化将不起作用。

希望有所帮助。

只是为Diogo的答案添加一个更明显的评论,这是正确的,但在我的情况下需要在父类的子列表中添加JsonProperty

 [Serializable] public class Titles { [JsonProperty("Titles")] public List TheTitles { get; set; } }