【问题标题】:Return json with parent/root node in web api在 web api 中返回带有父/根节点的 json
【发布时间】:2016-09-13 05:42:25
【问题描述】:

我正在尝试使用 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
    }
]

【问题讨论】:

  • 你有什么问题?
  • 你从哪里调用这个 api?
  • @CuongLe 我想要 Json 之前的父节点。有什么方法可以做到这一点?
  • @KarthikMR 直接通过浏览器调用。
  • 这种情况是什么父节点?

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


【解决方案1】:

我想你想要的是这样的

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

【讨论】:

  • 我试过这个,但我得到了一个 InvalidOperationException 指示 f__AnonymousType4 不能被序列化。
猜你喜欢
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多