【问题标题】:Deserialize JSON string for list to c# object将列表的 JSON 字符串反序列化为 c# 对象
【发布时间】:2021-07-28 21:33:14
【问题描述】:

我正在使用 C# jquery ajax json 处理 .netcore asp.net 项目,我从 ajax 调用传递模型并以字符串格式接收数据(formdata),但无法将EmployeesList 的数据从字符串对象转换为列表对象。

ajax 代码

$('#bttn_Click').click(function () {
                debugger;                
                var empListVal = null;
                empListVal = [];
                $('input:checkbox:checked').each(function () {
                    empListVal .push($(this).attr('value'));
                });
                var Emp_des_ViewModel = {
                    Designation: des_Value,
                    Department: dep_Value,                    
                    EmployeesList: empListVal 
                };                
                $.ajax({
                    type: "post",                    
                    data: "formData=" + JSON.stringify(Emp_des_ViewModel),
                    url: '/Emp_Designation_Assign/InsertDesignation',
                    datatype: "json",
                    success: function (result) {
                        alert(result);
                        window.location.href = "/Emp_Designation_Assign/InsertDesignation";
                        console.log(result);
                    }
                });
            });

Emp_des_ViewModel.cs

public class Emp_des_ViewModel 
    {
        public string Designation{ get; set; }
        public string Department{ get; set; }
        public List<SelectListItem> EmployeesList{ get; set; }
    }

Emp_Designation_AssignController.cs

[HttpPost]
    public IActionResult InsertDesignation(string formData)
    {
       var formdata = JsonConvert.DeserializeObject(formData);
       Emp_des_ViewModel emp_desViewModel = new Emp_des_ViewModel();
       emp_desViewModel = (Emp_des_ViewModel)formdata;
       //other code

    }

【问题讨论】:

  • 您不需要手动反序列化请求。如果 JSON 字符串实际上与 DTO 匹配,您可以将签名更改为 InsertDesignation(Emp_des_ViewModel emp_desViewModel)。如果没有,手动反序列化也不起作用。您发布的代码肯定是错误的。您不能只是将任意对象转换为不同的类型。如果你使用JsonConvert.DeserializeObject&lt; Emp_des_ViewModel&gt;(formData)`,你会得到你想要的对象。
  • JSON 字符串是什么样的?
  • 嗨@Niraj-stack,我的回答是否帮助您解决了您的问题?如果可以,请您接受作为答案吗?如果没有,请您跟进让我知道吗?参考:@ 987654321@.Thanks.

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


【解决方案1】:

我相信你的 ajax 应该是这样的

$('#bttn_Click').click(function () {
            debugger;                
            var empListVal = null;
            empListVal = [];
            $('input:checkbox:checked').each(function () {
                empListVal .push($(this).attr('value'));
            });
            var Emp_des_ViewModel = {
                Designation: des_Value,
                Department: dep_Value,                    
                EmployeesList: empListVal 
            };                
            $.ajax({
                type: "post",           
                contentType: 'application/json',         
                data: JSON.stringify(Emp_des_ViewModel),
                url: '/Emp_Designation_Assign/InsertDesignation'
                }).done(function (result) {
                    alert(result);
                    window.location.href = "/Emp_Designation_Assign/InsertDesignation";
                    console.log(result);
            });
        });

避免使用success,而是使用.done()。我不是解释原因的最佳人选,请查看here 了解更多详情。 在你的控制器中,你可以这样做

public IActionResult InsertDesignation([FromBody]Emp_des_ViewModel formData)
{
   Emp_des_ViewModel emp_desViewModel = formdata;
   //other code
}

如果 JSON 与您的模型兼容,.Net 将自动为您处理反序列化。

【讨论】:

    【解决方案2】:

    你这里有一些错误:

    1. 将json字符串反序列化为模型的正确方法应该是(顺便说一句,正如其他社区所说,不需要反序列化 json 手动,只需发送模型和默认值模型绑定系统将帮助您反序列化为模型):

      var formdata = JsonConvert.DeserializeObject<Emp_des_ViewModel>(formData);
      
    2. 你的模型中的EmployeesListList&lt;SelectListItem&gt;的类型,你可以查看下面SelectListItem的源代码,它 包含Disabled,Group,Selected,TextValue 属性:

      public class SelectListItem
      {              
          public SelectListItem();
      
          public SelectListItem(string text, string value, bool selected);
      
          public SelectListItem(string text, string value, bool selected, bool disabled);
      
          public bool Disabled { get; set; }
      
          public SelectListGroup Group { get; set; }
      
          public bool Selected { get; set; }
      
          public string Value { get; set; }
      }
      

      所以你需要发送如下数据:

      empListVal.push({ "PropertyName": "CheckedValue1" }, {"PropertyName":"CheckedValue2"});
      

      在您的代码中可能应该是:

      empListVal .push({ "PropertyName":$(this).attr('value')});
      
    3. 如果你必须坚持以你过去的方式发送 json(empListVal .push($(this).attr('value'));),你需要改变 你的模型:

      public class Emp_des_ViewModel
      {
          public string Designation { get; set; }
          public string Department { get; set; }
          public List<string> EmployeesList { get; set; }
      }
      

    完整的工作演示您可以关注:

    1. 型号:

      public class Emp_des_ViewModel
      {
          public string Designation { get; set; }
          public string Department { get; set; }
          public List<SelectListItem> EmployeesList { get; set; }
      }
      
    2. 查看:

      <button type="button" id="bttn_Click">click</button>
      @section Scripts
          {
          <script>
              $('#bttn_Click').click(function () {
                  debugger;
                  var empListVal = null;
                  empListVal = [];
                  empListVal.push({ "Value": "emp1" }, { "Value": "emp2" });
                  var Emp_des_ViewModel = {
                      Designation: "aaa",
                      Department: "bbb",
                      EmployeesList: empListVal
                  };
                  $.ajax({
                      type: "post",
                      contentType: 'application/json',
                      data: JSON.stringify(Emp_des_ViewModel),
                      url: '/Emp_Designation_Assign/InsertDesignation',
                      datatype: "json",
                      success: function (result) {
                          //...
                      }
                  });
              });
          </script>
      }
      
    3. 控制器:

      [HttpPost]
      public IActionResult InsertDesignation([FromBody]Emp_des_ViewModel formData)
      {
          //other code
          return Json(formData);
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2019-05-30
      • 1970-01-01
      相关资源
      最近更新 更多