Search code examples
c#jsonasp.net-web-apiserializationwebapi

How To Make C# Web API Return Values Only, Not Keys


I am working on a Web API in C#, and would like to return the values only, as opposed to the keys. I am getting the data from a DataSet and so far this is what I have;

{
    "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

What I would like is for the return to look like the below;

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

In my Controller, I am getting the data like so;

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

Is there a way to ignore the Property Keys (or column names(?)) and return just the Values? Many thanks in advance.


Solution

  • you have a bug in your code, you have created studentRoles but you are returning ds. Fix it and fix the code to something like this

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