【问题标题】:How to deserialize a json string with C# ASP MVC如何使用 C# ASP MVC 反序列化 json 字符串
【发布时间】:2015-10-22 20:52:41
【问题描述】:

我有一个带有一些 Ajax 调用的 ASP MVC 项目,我试图从 jquery/Ajax 传递到我的 AjaxController(参见下面的代码),其中控制器 sting 项正在接收这样的 json 字符串

"[\n  \"1002\",\n  \"1003\"\n]"

我在控制器中收到此错误(请参阅下面的代码,其中注释标识了错误)

Newtonsoft.Json.JsonSerializationException: Error converting value "1002" to type 'System.String[]'. Path '[0]', line 2, position 9. ---> System.ArgumentException: Could not cast or convert from System.String to System.String[]. at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType) at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType) ...(continue)

这是我的 Json/Jquery 创建函数

function SaveObservations() {
        var SerSel = $("#ServiceIdSelect2").val();
        var obs = $("#observation").val();
        var itemsX = [];
        if (obs == "") {
            mostrar_alert_ui("Validation message", "Observation cannot be null", 350);
        } else {
            //Start json creation
            $("#ItemsPieces > input:checked").each(function () {
                var id = $(this).val();
                itemsX.push(id);
            });
            var itemsY = JSON.stringify(itemsX, null, 2);
            //End json creation
            Funciones_Ajax_conAlert("/Ajax/SendEmailItemsToClient/", { proyecto: SerSel, items: itemsY, observation: obs }, CloseObservations);
        }
    }

这是我的控制器给出错误的地方

public JsonResult SendEmailItemsToClient(int proyecto, string items, string observation) 
        {
            object data = null;
            try
            {

                List<string[]> datax1 = JsonConvert.DeserializeObject<List<string[]>>(items); //Here is the issue Aqui tengo el problema

                foreach (var item in datax1) 
                {
                    string test = item.ToString();
                }
                string mensaje = "";
                int ProjectIdx = proyecto;
                bool resp = CorreccionesController.SendItemsDifferentsToClient(ProjectIdx, mensaje);
                if (resp) { 
                    data = new
                    {
                        success = true,
                        titulo = "Notification",
                        mensaje = "A message explaining why the different items selected are used had been sent"
                    };
                } 
                else 
                {
                    data = new
                    {
                        success = false,
                        titulo = "Notification",
                        mensaje = "The observation is Saved but the email couldn't be send, please contact support"
                    };
                }
            }
            catch (Exception ex) 
            {
                data = new
                {
                    success = false,
                    titulo = "ERROR",
                    mensaje = ex.ToString()
                };
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }

问题是如何在不收到错误的情况下迭代该 json 字符串?

【问题讨论】:

  • 将参数更改为string[] items(您发送的是一组值,而不是单个值)
  • List&lt;string[]&gt; 更改为List&lt;string&gt;
  • @Hackerman 谢谢我用你的解决方案解决了,你能否用更完整的答案回答这个问题,以便我接受并给你+1?
  • 好的,我会尽快提供答案。
  • @RicardoRios,完成......请检查我的答案。

标签: c# jquery asp.net json asp.net-mvc


【解决方案1】:

您的代码需要一点重构;基本上你有一个像这样的 json 结构:

[
  "1002",
  "1003"
]

基本上就是Array of Strings

在您的控制器中,您有以下行:

List<string[]> datax1 = JsonConvert.DeserializeObject<List<string[]>>(items); 

现在,这段代码List&lt;string[]&gt; 是什么意思?使用该行,您正在尝试创建一个字符串数组列表,如下所示:

[
  ["1002","1003"],
  ["1002","1003"]
]

因此,您的反序列化方法失败并显示以下消息:Could not cast or convert from System.String to System.String[]。现在说得通了。

所以如果你想反序列化一个 json 字符串数组,你只需要:

List<string> datax1 = JsonConvert.DeserializeObject<List<string>>(items); 

List&lt;string&gt; 就像字符串数组(内部是基于数组构建的列表,请查看此答案以获取有关数组和列表的更多信息:Array versus List<T>: When to use which?

根据这些信息,您也可以这样编写代码:

string[] datax1 = JsonConvert.DeserializeObject<string[]>(items); //Not tested, but should works.

【讨论】:

    【解决方案2】:

    不要重复 Json 编码,让 WebAPI 完成所有工作:

    function SaveObservations() {
            var SerSel = $("#ServiceIdSelect2").val();
            var obs = $("#observation").val();
            var itemsX = [];
            if (obs == "") {
                mostrar_alert_ui("Validation message", "Observation cannot be null", 350);
            } else {
                //Start json creation
                $("#ItemsPieces > input:checked").each(function () {
                    var id = $(this).val();
                    itemsX.push(id);
                });
    
                //End json creation
                Funciones_Ajax_conAlert("/Ajax/SendEmailItemsToClient/", { proyecto: SerSel, items: itemsX, observation: obs }, CloseObservations);
            }
        }
    

    public JsonResult SendEmailItemsToClient(int proyecto, string[] items, string observation) 
        {
            object data = null;
            try
            {
    
                foreach (var item in items) 
                {
                    string test = item.ToString();
                }
                string mensaje = "";
                int ProjectIdx = proyecto;
                bool resp = CorreccionesController.SendItemsDifferentsToClient(ProjectIdx, mensaje);
                if (resp) { 
                    data = new
                    {
                        success = true,
                        titulo = "Notification",
                        mensaje = "A message explaining why the different items selected are used had been sent"
                    };
                } 
                else 
                {
                    data = new
                    {
                        success = false,
                        titulo = "Notification",
                        mensaje = "The observation is Saved but the email couldn't be send, please contact support"
                    };
                }
            }
            catch (Exception ex) 
            {
                data = new
                {
                    success = false,
                    titulo = "ERROR",
                    mensaje = ex.ToString()
                };
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2020-09-14
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多