0

thank you in advance for your contributions. I am passing a JSON string to a .NET controller and parsing it in a C# class. Here is my JSON..

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

Here is a snippet of my C# class defining the JSON variables (not including the nested array).

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

And here is a snippet of my C# class that is parsing the JSON

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

Currently, all of this code works but now I need to access that nested array "Items" in the JSON. How do I declare that correctly in the code above? I tried Array but that did not work.

  • 1
    Use one of the tools from [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/q/21611674/3744182) to generate a data model for you. You will need to add a `public List Items { get; set; }` to `CreateOrderRequest` where `Item` looks like `public class Item { public long ItemId { get; set; } public string ItemDesc { get; set; } }`. – dbc Apr 03 '21 at 22:29
  • `I tried Array but that did not work` - Can you include what you tried? How did it not work? Did you get an error? – devNull Apr 04 '21 at 01:46

1 Answers1

1

A List will work:

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

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

}
tymtam
  • 31,798
  • 8
  • 86
  • 126