C#(ASP.NET)反序列化异常

本文关键字:反序列化 异常 NET ASP | 更新日期: 2023-09-27 18:01:00

我正在学习将ASP.NET MVC与AngularJS一起使用。

首先,我们可以看看我在服务器上执行POST请求的AngularJS代码:

$http({
                method: 'POST',
                url: '/Test/PostForm',
                dataType: "json",
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;' },
                data: $.param({
                    data: JSON.stringify($scope.productos),   
                }, true)
            })
            .success(function (data, status, headers, config) {
                console.log(data);
            })
            .error(function (data, status, headers, config) {
                console.log(data, status, headers, config);
            })

其中:

$scope.productos = [ {desc:"Product 1", cant: 10, cu:100}, {desc:"Product 2", cant: 10, cu:100} ...]

我决定在我的$scope.productos上使用JSON.stringify方法将其传递给我的操作,如下所示:

public JsonResult PostForm(string data)
    {
        System.Diagnostics.Debug.WriteLine(data);
        Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(data); // Exception thrown here
        System.Diagnostics.Debug.WriteLine("-------------------");
        
        System.Diagnostics.Debug.WriteLine("-------------------");
        string[] arr = { "Success", "Los archivos han sido agregados correctamente" };
        return Json(arr, JsonRequestBehavior.DenyGet);
    }

我的问题出现在尝试执行Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);时,因为我得到了一个异常:

无法将当前JSON数组(例如[1,2,3](反序列化为类型"System.Collections.Generic.Dictionary `2[System.String,System.String]",因为该类型需要JSON对象(例如{"name"value"}(才能正确反序列化。

要修复此错误,请将JSON更改为JSON对象(例如{"name":"value"}(,或者将反序列化的类型更改为数组或实现集合接口(例如ICollection、IList(的类型,如可以从JSON数组反序列化的List。JsonArrayAttribute也可以添加到类型中,以强制它从JSON数组反序列化。

你知道怎么修吗?它应该得到一个有效的JSON字符串,因为我在.cshtml.上的JSON.stringify上没有得到任何错误

我要做的是将字符串内容unpack放入数组或字典中。

C#(ASP.NET)反序列化异常

首先,您需要定义一个类来将JSON字符串反序列化为。例如:

public class Producto 
{
     [JsonProperty("desc")]
     public string Descripcion{get;set;}
     [JsonProperty("cant")]
     public int Cantidad{get;set;}
     [JsonProperty("cu")]
     public int CostoPorUnidad{get;set;}
}

然后,您可以将data字符串反序列化为Producto:的数组

var productos = JsonConvert.DeserializeObject<Producto[]>(data);

或者通过使用LINQ:将其编入词典

var productos = JsonConvert.DeserializeObject<Producto[]>(data).ToDictionary(p=>p.Descripcion);