在web api中返回带有父节点/根节点的json

时间:2016-05-17 08:22:28

标签: json asp.net-mvc asp.net-web-api asp.net-web-api2

我正在尝试使用web api从数据库表返回JSON。

控制器

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);
}

位置模型:

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

任何人都可以帮忙吗?如何使用父/节点返回JSON?当我运行上面的代码时,它显示以下输出

[
    {
        "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
    }
]

1 个答案:

答案 0 :(得分:2)

我认为你想要的是这样的

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

我是对的吗?

如果是这样,您的操作的返回类型不能是IEnumerable或数组。

您需要做的是返回一个包含数组属性的对象。

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) };
}