Ali
Ali

Reputation: 45

ASP.NET Core 3.1 Web API - custom json

In my project, I have a table called product (Id, name) it has 10K plus rows. I would return JSON object in the below format.

I have a Product class in C# (Id, name). When I do Http get it return [{id: "", name:""},{id: "", name:""}]. I would like to warp return array of "Product" :[]

Current return is

[
    {
        "id": "3089e0d5-476f-407a-9458-949d0d08123f"
         "name": "Laptop"
     },
     {
        "id": "3089e0d5-476f-407a-9458-949d0d08123f"
         "name": "Mobile"
     }
  ]

Desired result is:

  "product":
    [
    {
        "id": "3089e0d5-476f-407a-9458-949d0d08123f"
         "name": "Laptop"
     },
     {
        "id": "3089e0d5-476f-407a-9458-949d0d08123f"
         "name": "Mobile"
     }
  ]

Please advice

Upvotes: 0

Views: 192

Answers (1)

Yiyi You
Yiyi You

Reputation: 18159

1.you can try to use the following code directly:

return Ok(new { products = _mapper.Map<IEnumerable<Models.ProductDto>>(proRepo) });

2.Another way,you can try to create

 public class ViewModel
    {
        public List<Product> product { get; set; }
      
    }

and then use

return Ok(new ViewModel{ products = _mapper.Map<IEnumerable<Models.ProductDto>>(proRepo) });

Upvotes: 1

Related Questions