json 如何使C# Web API仅返回值而不返回键

jvidinwx  于 2023-02-14  发布在  C#
关注(0)|答案(1)|浏览(209)

我正在用C#开发一个API,并且希望只返回值,而不是键。我从数据集中获取数据,到目前为止,这就是我所拥有的;

{
    "Role": [
        {
            "PersonName": "Test, Student1",
            "UserName": "12345",
            "Profile": "STUDENT",
            "Level": "UN",
            "Year": 1,
            "Department": null
        },
        {
            "PersonName": "Test, Student2",
            "UserName": "678910",
            "Profile": "STUDENT",
            "Level": "UN",
            "Year": 1,
            "Department": null
        }, etc

我想要的是回报看起来像下面;

{
    "Role": [
        {
            "Test, Student1",
            "12345",
            "STUDENT",
            "UN",
            1,
            null
        },
        {
            "Test, Student2",
            "678910",
            "STUDENT",
            "UN",
            1,
            null
        }, etc

在我的控制器中,我像这样获取数据;

List<Roles> studentRoles = new List<Roles>();
           public HttpResponseMessage Get() 
*****some connections here and sql query which I have not included as perhaps irrelevant*****

           sda.Fill(ds, "Role");
            foreach (DataRow drow in ds.Tables[0].Rows)
            {
                studentRoles.Add(new Roles
                {
                    PersonName = (string)drow["PersonName"],
                    UserName = (string)drow["UserName"],
                    Profile = (string)drow["Profile"],
                    Level = (string)drow["Level"],
                    Year = Convert.ToInt32(drow["Year"]),
                    Department = (drow["Department"] == DBNull.Value) ? "No Department" : drow["Department"].ToString()

                });
            }

            return Request.CreateResponse(HttpStatusCode.OK, ds);

有没有办法忽略属性键(或列名(?))而只返回值?非常感谢。

nafvub8i

nafvub8i1#

您的代码中有一个错误,您创建了studentRoles,但返回了ds。请修复该错误,并将代码修复为类似以下内容

List<List<object>> studentRoles = new List<List<object>>();

    foreach (DataRow drow in ds.Tables[0].Rows)
    {
        var item = new List<object>();

        item.Add((string)drow["PersonName"]);
        item.Add((string)drow["UserName"]);
        //....
        studentRoles.Add(item);
    };

    return Request.CreateResponse(HttpStatusCode.OK, new { Role= studentRoles });

相关问题