问题描述
我有这样的code和当我执行它这种不断显示了同样的错误:无效的JSON原始:标题
I have this code, and when i'm executing it this keeps showing the same error: Invalid JSON primitive: titles.
客户端:
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数组JSON和在ashx的处理程序收到
字符串[]是不是有效的泛型类型为操作;字符串没有参数的构造函数所以当串行器尝试了新一轮上涨,它失败。此外,你已经从sr.ReadToEnd(字符串),所以你没有真正deserialising,它更像是你问它来解析和分割字符串你,它不能做。
的JavaScriptSerializer是pretty无情的,老实说我最后总是试图deserialise这样的一个阵列时撕裂我的头发......你是好得多在服务器端定义DTO类来处理映射
JavaScriptSerializer is pretty unforgiving and to be honest I always end up tearing my hair out when trying to deserialise an array like this...you are much better off defining a DTO class on the server side to handle the mapping:
[Serializable]
public class Titles
{
public List<Title> TheTitles { get; set; }
}
[Serializable]
public class Title
{
public string title { get; set; }
}
所以,现在你的处理程序是这样的:
So now your handler looks like this:
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是这样的:
And your AJAX is like this:
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对象属性的完全定义相匹配,如果它不那么deserialisation将无法工作。
Note how the definition of the DTO classes matches exactly the definition of the JSON object properties, if it doesn't then the deserialisation will not work.
希望有所帮助。
这篇关于发送JSON数组ASHX处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!