【问题标题】:Changing JSON return object names更改 JSON 返回对象名称
【发布时间】:2019-06-26 11:50:56
【问题描述】:

我有这个功能用于返回用户和用户数

List<User> entitiesList = DB.Users.OrderBy(x => x.UserName).ToList();
var count = DB.Users.Count
return (entitiesList, count)

HTTP 请求的结果是这样的

{
    "item1":
[
    {
        "fullName":"Joe Smith"
    },
    {"fullName":"Bob Rogan"
    }
]
    "item2":["2"]
}

问题是为什么 JSON 结果有名为 item1 和 item2 的对象,这些名称是从哪里来的,我没有在任何地方指定这样的名称,在这种情况下不应该没有名称吗?以及如何将“item1”重命名为“users”,将“item2”重命名为“count”?

【问题讨论】:

    标签: asp.net-core model-view-controller


    【解决方案1】:

    这是因为您返回一个元组,在您的情况下(类用户,整数)。您应该返回一个自定义类:

    public class Response {
        public List<User> Users;
        public int Count;
    }
    

    ....

    return (new Response { Users = entitiesList, Count = count}); 
    

    【讨论】:

      猜你喜欢
      • 2016-08-22
      • 2012-09-26
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      相关资源
      最近更新 更多