Search code examples
jsonasp.net-corejquery-select2

Format JSON Result


Json data returned from my ASP.NET core server with:

JsonConvert.SerializeObject(categories.Select(t => new { id = t.Id.ToString(), text = t.Name.ToLower() }))

Looks:

[
{
    "id": "7929d7ad-c7c3-45c5-b749-7633a478d55c",
    "text": "apparel"
},
{
    "id": "e551cbc2-9069-4c99-a66b-5824ec2610b2",
    "text": "electronics"
}]

But I want result like:

{"results":[
{
    "id": "7929d7ad-c7c3-45c5-b749-7633a478d55c",
    "text": "apparel"
},
{
    "id": "e551cbc2-9069-4c99-a66b-5824ec2610b2",
    "text": "electronics"
}]}

for select2. How can I achieve that?


Solution

  • try this

    JsonConvert.SerializeObject( new { 
    results = categories.Select(t => new { id = t.Id.ToString(), text = t.Name.ToLower() }) 
    } );