Anwar Ul-haq
Anwar Ul-haq

Reputation: 1881

IEnumerable C# object to JSON object of arrays with name

 public IEnumerable<Product> GetAllProdcut()
 {
     var products= _productRepository.GetAllProduct();
     return products;
 }

The above code returns the following JSON object:

[  
    {  
      "$id":"1",
      "Id":1,      
      "Name":"Dave",
      "Department":"IT",
    },
    {  
       "$id":"2",
      "Id":2,      
      "Name":"Dave",
      "Department":"IT",
    },
    {  
      "$id":"3",
      "Id":3,      
      "Name":"Dave",
      "Department":"IT",
    },
    {  
       "$id":"4",
      "Id":4,      
      "Name":"Dave",
      "Department":"IT",
    }
]

What I need is to add { "data": at the beginning and } at the end.

What's the best way to add { "data": at the beginning and } at the end?

I don't want to use string concatenation.

Thank you.

Upvotes: 1

Views: 316

Answers (1)

lame_coder
lame_coder

Reputation: 3115

You just have to return an anonymous object:

public object GetAllProduct()
{
    var products= _productRepository.GetAllProduct();
    return new { data = products };
}

Here is a fiddle demo - https://dotnetfiddle.net/nKRsnQ

Upvotes: 5

Related Questions