Home > Back-end >  Passing Object to Array through Injection in .NET
Passing Object to Array through Injection in .NET

Time:12-21

I don't really know how to explain this but I'm having a really difficult time getting my code to work.

I'm working on a Web API in .NET and have this model in my code:

public class NewBasketDTO
    {

        public string Identifier { get; set; }
        public Array Items { get; set; }
    }

What I want to achieve here is that I want to be able to pass through objects to my Array like this in JSON format:

{
   identifier: "someidentifier",
   items: [
      { productId: 1, quantity: 1 },
      { productId: 3, quantity: 2 },
      { productId: 4, quantity: 1 }
   ]
}

But I'm having huge problems since in PostMan I'm getting this error:

System.NotSupportedException: The collection type 'System.Array' is abstract, an interface, or is read only, and could not be instantiated and populated. Path: $.items | LineNumber: 2 | BytePositionInLine: 12.

How do I pass objects to my public Array Itmes?

I've searched this up and found no sufficient answer, thanks in advance for any help

CodePudding user response:

System.Array is an abstract class and cannot be instantiated. You probably want to define Items as a List<ItemDTO> type.

public class ItemDTO
{
    public int ProductId { get; set; }
    public int Quantity { get; set; }
}

public class NewBasketDTO
{
    public string Identifier { get; set; }
    public List<ItemDTO> Items { get; set; }
}

Alternately you could use an array of ItemDTO:

public class NewBasketDTO
{
    public string Identifier { get; set; }
    public ItemDTO[] Items { get; set; }
}
  • Related