steve_c123
steve_c123

Reputation: 69

Adding root identifier to JSON

I have a controller which returns my SalesOrder DTO as JSON as follows:

{
    "SalesOrderId": 19550,
    "OrderNumber": "1625-002-19550"
}

I need to return it as such:

{
    "SalesOrder": [
        {
            "SalesOrderId": 19550,
            "OrderNumber": "1625-002-19550"
        }
    ]
}

My Controller:

public class SalesOrderController : Controller
{
    [HttpGet("{id}")]
    [Route("[action]/{id}/")]
    public async Task<Object> GetSalesOrderReport(int id)
    {
        try
        {
            return Json(await SalesOrderService.GetSalesOrderReport(id));
        }
        catch (Exception ex)
        {
            return Json(new { code = "422", success = false, message = "Unable to fetch sales orders - " + ex.ToString() });
        }
    }
}    

My service returns a SalesOrder DTO.

public class SalesOrderViewModel
{
    public int SalesOrderId { get; set; }
    public string OrderNumber { get; set; }
}

Can I do this using Annotations or is there a better way to achieve this?

Upvotes: 0

Views: 97

Answers (1)

Halil İbrahim
Halil İbrahim

Reputation: 144

This is the model which will give you the output type you are asking for.

public class SalesOrderRoot 
{
     public List<SalesOrderViewModel> SalesOrders {get; set;}
}

or you can do

return Json(new { SalesOrder = new List<SalesOrderViewModel>
{ 
  (await SalesOrderService.GetSalesOrderReport(id))
}

Upvotes: 1

Related Questions