【问题标题】:How to deserialize a multidimensional angular json using c#如何使用 c# 反序列化多维角度 json
【发布时间】:2018-05-26 19:51:37
【问题描述】:
var data2 = results.FormData["model2"];

下面是来自 angular json data2 的示例输出,用于在 asp.net MVC web api 中进行转换

{
  "0":{"RowStamp":2,"Department":"Billing and Collection"},
  "1":{"RowStamp":7,"Department":"Business Development"},
  "2":{"RowStamp":10,"Department":"Construction Management/Design"}
}

我有模型课

public class DeptModel
{
    public int RowStamp { get; set; }
    public string Department { get; set; }
}

var dictionary = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<DeptModel>(data2); 

调试时出错

Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List

有人可以帮我反序列化这个模型吗?如果提供示例代码会更好。提前致谢

【问题讨论】:

  • 你有代表类似结构的类吗?您是否尝试将其用作操作方法参数?请分享相关代码
  • 你需要一个模型类同时包含属性RowStamp & Department,然后使用JavaScriptSerializer.Deserialize方法或类似的方法来反序列化JSON对象。
  • 你为什么不用Json.net又名Newtonsoft.Json
  • 对我来说看起来像是一个类列表.....用 Newtonsoft 很容易
  • 使用反序列化)> ...抱歉我的平板电脑不好,无法轻松输入

标签: c# asp.net angularjs asp.net-mvc


【解决方案1】:

这个问题解决了

型号

public class DeptModel
{
    public int RowStamp { get; set; }
    public string Department { get; set; }
}

反序列化为模型

var data2 = results.FormData["model2"];
var dictionary = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, DeptModel>>(data2); 

【讨论】:

    【解决方案2】:

    在usings部分添加

    using Newtonsoft.Json.Linq;
    

    并使用以下代码:

    var request = JArray.Parse(data2);
    var dictionaryResult = keyResponse.ToObject<List<Dictionary<string, DeptModel>>>();
    

    【讨论】:

      【解决方案3】:

      这样你就可以用Newtonsoft.Json反序列化你的JSON

      const string json = @"
      {
          ""0"":{""RowStamp"":2,""Department"":""Billing and Collection""},
          ""1"":{""RowStamp"":7,""Department"":""Business Development""},
          ""2"":{""RowStamp"":10,""Department"":""Construction Management/Design""}
      }";
      
      Dictionary<string, DeptModel> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, DeptModel>>(json);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-31
        • 1970-01-01
        • 2015-03-11
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        相关资源
        最近更新 更多