【问题标题】:Accessing Nested Array in JSON in C# .NET Core在 C# .NET Core 中访问 JSON 中的嵌套数组
【发布时间】:2021-04-03 22:02:01
【问题描述】:

提前感谢您的贡献。我将 JSON 字符串传递给 .NET 控制器并在 C# 类中对其进行解析。这是我的 JSON..

{"CusEmail":"foo-bar@gmail.com","Name":"Foo Bar",
    "Items":[{"ItemId":1234,"ItemDesc":"Item-1234"},{"ItemId":5678,"ItemDesc":"Item-5678"}]
}

这是我的 C# 类的 sn-p 定义 JSON 变量(不包括嵌套数组)。

public class CreateOrderRequest
{
    public string CusEmail { get; set; }
    public string Name { get; set; }
}

这是解析 JSON 的 C# 类的 sn-p

 public JsonResult CreateShipTo(CreateOrderRequest createOrderRequest)
 {
       ... parsing code here
 }

目前,所有这些代码都有效,但现在我需要访问 JSON 中的嵌套数组“Items”。如何在上面的代码中正确声明?我尝试了 Array 但没有奏效。

【问题讨论】:

  • 使用How to auto-generate a C# class file from a JSON string 中的一种工具为您生成数据模型。您需要将public List<Item> Items { get; set; } 添加到CreateOrderRequest,其中Item 看起来像public class Item { public long ItemId { get; set; } public string ItemDesc { get; set; } }
  • I tried Array but that did not work - 你能包括你试过的吗?怎么没用?你收到错误了吗?

标签: c# json .net


【解决方案1】:

列表将起作用:

public class Item
{
    public int ItemId { get; set; }
    public string ItemDesc { get; set; }
}

public class WithItems
{
    public List<Item> Items { get; set; }

}

【讨论】:

    猜你喜欢
    • 2021-01-22
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多