Home > Software design >  Entity Framework: How to get desired json response?
Entity Framework: How to get desired json response?

Time:12-31

I have a really simple web api, and it is working without any issue, but I am not getting response in desired format.

My GET Method:

[HttpGet("{tickers}")]
    public async Task<ActionResult<DbDataRecord>> getPrice(string tickers)
    {

        string[] ticks= tickers.Split(',');
        //var _data = await _dbContext.Prices.ToListAsync();
        var _data = _dbContext.Prices.Where(p => ticks.Contains(p.Ticker))
                                     .Select(p => new {p.Ticker,p.PriceDate,p.ChangePercent})
                                     .OrderBy(p=> p.PriceDate);

        return _data == null ? NotFound() : Ok(_data);
       
    }

This is my response:

[
    {
        "ticker": "TCS",
        "priceDate": "2021-08-02",
        "changePercent": 0
     },
     {
        "ticker": "ITC",
        "priceDate": "2021-08-02",
        "changePercent": 0
     },
     {
         "ticker": "ITC",
         "priceDate": "2021-08-03",
         "changePercent": 1.2577663282315548
      },
      {
         "ticker": "TCS",
         "priceDate": "2021-08-03",
         "changePercent": 2.0344583431673384
      }
  ]

I want the response in this format (desired response):

[
    {
        "ticker": "TCS",
        "change":[{"priceDate": "2021-08-02","changePercent": 0},
                  {"priceDate": "2021-08-03","changePercent": 2.0344583431673384}]
    },
    {
        "ticker": "ITC",
        "change":[{"priceDate": "2021-08-02","changePercent": 0},
                  {"priceDate": "2021-08-03","changePercent": 1.2577663282315548}]
    }
]

CodePudding user response:

One way of doing, is to use GroupBy after the data was fetched from the database.

var _nestedData = _data.GroupBy(x => x.Ticker)
.Select(g => new
{
    Ticker = g.Key,
    Change = _data.Where(y => y.Ticker == g.Key)
 .Select(p => new { p.PriceDate, p.ChangePercent }).ToList()
}).ToList();

return _nestedData == null ? NotFound() : Ok(_nestedData);
  • Related