【问题标题】:Pass Nested Deserialized JSON from Controller to View将嵌套的反序列化 JSON 从控制器传递到视图
【发布时间】:2019-08-04 09:43:58
【问题描述】:

在使用 HttpClient 类将我的 JSON 转换为字符串并使用

反序列化之后
var response = Res.Content.ReadAsStringAsync().Result;

data = JsonConvert.DeserializeObject<List<Employee>>(response);

如何使用下面的模型将我在控制器中收到的数据从调用传递到视图?

        public class RuleType
        {
            public int Id { get; set; }
            public string Description { get; set; }
            public bool Inactive { get; set; }
        }

        public class RuleCategory
        {
            public int Id { get; set; }
            public string Description { get; set; }
            public bool Inactive { get; set; }
        }

        public class Employee
        {
            public string Description { get; set; }
            public object EndDateTime { get; set; }
            public int Id { get; set; }
            public bool Inactive { get; set; }
            public int RuleAction { get; set; }
            public DateTime StartDateTime { get; set; }
            public RuleType RuleType { get; set; }
            public RuleCategory RuleCategory { get; set; }
        }

这是调用中的一个对象

[
    {
        "Description": "Test Description",
        "EndDateTime": null,
        "Id": 1,
        "Inactive": false,
        "RuleAction": -2,
        "StartDateTime": "2017-01-06T14:58:58Z",
        "RuleType": {
            "Id": 6,
            "Description": "Test Description",
            "Inactive": false
        },
        "RuleCategory": {
            "Id": 1,
            "Description": "Description",
            "Inactive": false
        }
    }
]

【问题讨论】:

  • 该 JSON 字符串包含 RootObject 实例的数组,而不是 Employee 对象。 Employee 没有 any 属性,因此无需(反)序列化
  • 好的,我明白了,谢谢。所以我应该删除包含的 Employee 类?

标签: c# .net json model-view-controller httpclient


【解决方案1】:

不确定我是否遗漏了什么,但如果您有一个对象想要从控制器返回到视图,您只需:

return View(viewModel); // in your case viewModel = 'data'

【讨论】:

  • 谢谢乔纳森。我已经返回,但在我的 foreach (var item in Model) 循环中,我现在收到消息 System.NullReferenceException: Object reference not set to an instance of an object。
  • 所以 viewModel 或者它的一部分,没有预期的东西。在您返回并检查 viewModel 之前,在控制器中放置一个断点。您的序列化可能无法按预期工作。如果是这样,您的问题不正确,因为将嵌套数据传递给视图不会成为问题
【解决方案2】:

正如其他人已经说过的那样,您应该将 JSON 反序列化为 RootObject 而不是像这样的 Employee:

var response = Res.Content.ReadAsStringAsync().Result;
var data = JsonConvert.DeserializeObject<List<RootObject>>(response);

然后您可以使用以下方法将模型传递到视图中:

return View(data)

您还应该考虑将 RootObject 重命名为更有用的名称(例如员工?),因为 RootObject 不是一个很有用或描述性的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2020-12-19
    相关资源
    最近更新 更多