1

I have this code, and when i'm executing it this keeps showing the same error: Invalid JSON primitive: titles.

Client Side:

        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();
            }
        });

Server Side:

        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);
        }

Regards

4

2 回答 2

4

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

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

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 对象属性的定义完全匹配,如果不匹配,则反序列化将不起作用。

希望有帮助。

于 2013-11-08T15:06:50.363 回答
0

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

[Serializable]
 public class Titles
 {
    [JsonProperty("Titles")] 
    public List<Title> TheTitles { get; set; } 
 }
于 2016-01-26T21:21:50.013 回答