Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return json with parent/root node in web api

I am trying to return JSON from database table using web api.

Controller

private WebApiEntities dataContext = new WebApiEntities();
[ActionName("GetLocations")]
public IEnumerable<Location> GetLocations()
{
    //IEnumerable<Location> list = null;
    var list = (from c in dataContext.LocationMasters
                select new Location
                {
                    LocationId = c.LocationId,
                    LocationName = c.LocationName
                }).ToList();
    return list.OrderBy(c => c.LocationName);
}

Location Model :

public class Location
{
    public int LocationId { get; set; }
    public string LocationName { get; set; }
    public string LocationImage { get; set; }
}

Can any one help? How to return JSON with parent /node? When I run the above code it displays following output

[
    {
        "LocationId": 5,
        "LocationName": "AMBERNATH",
        "LocationImage": null
    },
    {
        "LocationId": 1,
        "LocationName": "BHIWANDI",
        "LocationImage": null
    },
    {
        "LocationId": 2,
        "LocationName": "KALYAN",
        "LocationImage": null
    },
    {
        "LocationId": 3,
        "LocationName": "THANE",
        "LocationImage": null
    },
    {
        "LocationId": 4,
        "LocationName": "ULHASNAGAR",
        "LocationImage": null
    }
]
like image 325
Parag Pathari Avatar asked Aug 31 '25 16:08

Parag Pathari


1 Answers

I think what you want is something like this

{
   "locations": [{
        "LocationId": 5,
        "LocationName": "AMBERNATH",
        "LocationImage": null
        },
        {
         "LocationId": 1,
        "LocationName": "BHIWANDI",
        "LocationImage": null
        }]
}

Am I right?

If so the return type of your action cannot be an IEnumerable or array.

What you need to do is return an object with a property containing your array.

public object GetLocations()
{
   //IEnumerable<Location> list = null;
   var list = (from c in dataContext.LocationMasters
            select new Location
            {
                LocationId = c.LocationId,
                LocationName = c.LocationName
            }).ToList();
   return new {location = list.OrderBy(c => c.LocationName) };
}
like image 118
Padraic Avatar answered Sep 02 '25 08:09

Padraic