1

Need a JSON response like this:

{
        "statusCode": 200,
        "errorMessage": "Success",
        "Employees": [
                {
                "empid": "7228",
                "name": "Tim",
                "address": "10815 BALTIMORE",
                
                },
               {
                "empid": "7240",
                "name": "Joe",
                "address": "10819 Manasas",
                }
            ]
}

Model Class:

public class EmployeeList
{
    public string empid { get; set; }
    public string name { get; set; }
    public string address { get; set; }
}


public class Employee
{
     public int statusCode { get; set; }
     public string errorMessage{ get; set; }
     public List<EmployeeList> Employees { get; set; }
}

Controller is like this:

List<Models.Employee> emp = new List<Models.Employee>();
//call to SP
if (rdr.HasRows)
    {
           
                var okresp = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    ReasonPhrase = "Success"
                };

                Models.Employee item = new Models.Employee();
                {
                    item.statusCode = Convert.ToInt32(okresp.StatusCode);
                    item.errorMessage = okresp.ReasonPhrase;
               
                    
                    while (rdr.Read())
                    {
                        item.Employees = new List<EmployeeList>{
                        new EmployeeList
                        { 
                            empid = Convert.ToString(rdr["empid"]),
                            name = Convert.ToString(rdr["name"]),
                            address = Convert.ToString(rdr["address"]) 
                        }};
                     }
                    
                };

    emp.add(item);

// return response

What should be my controller class code to create JSON array response while I read data from reader? I am not able to get the loop part of creating JSON array in response file. Am I assigning the values in While loop incorrectly?

  • which framework do you use? ASP.NET MVC ? ASP.NET Core ? Other ? – Pac0 Sep 15 '20 at 07:41
  • Does this answer your question? [How do I turn a C# object into a JSON string in .NET?](https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net) – Daniel Argüelles Sep 15 '20 at 07:44
  • 2
    Tip: you should rename EmployeeList to Employee (because is not a list) and Employee to EmployeeResponse or something similar – Daniel Argüelles Sep 15 '20 at 07:45
  • @DanielArgüelles Wanted to say the same. The current naming is rather strange. Also, the current `Employee` object seems to be a perfect representation of information, that HTTP provides already. If you want to return a valid object, just return it. If you want to provide an error, throw an exception. Or return a HttpResponse. There you can set the status code and content by yourself. – André Reichelt Sep 15 '20 at 07:49
  • @DanielArgüelles True, the naming is incorrect as it's an example. I'm able to serialize the result, but the result I'm getting is always the last row for Employees list. Maybe the iteration is not going well. Any reference to this type of issue. – pradevan thakur Sep 15 '20 at 08:11
  • How does your controller look like? – Pavel Anikhouski Sep 15 '20 at 09:13
  • @Pavel, added controller example. – pradevan thakur Sep 15 '20 at 09:38

1 Answers1

0

After your while (rdr.Read()), you reset item.Employees with a new List<EmployeeList> at every data. So you will be getting the last element every time.

Move your list initialisation outside of the loop and use the add method.

item.Employees = new List<EmployeeList>();
while (rdr.Read())
{
    item.Employees.Add(
        new EmployeeList
        { 
            empid = Convert.ToString(rdr["empid"]),
            name = Convert.ToString(rdr["name"]),
            address = Convert.ToString(rdr["address"]) 
        });
}
Drag and Drop
  • 2,672
  • 3
  • 25
  • 37
  • Note that it was all thanks to the information of your comment "_I'm getting is always the last row for Employees list_". I will advice taking a look at ORM like Dapper or LinQ2SQL, EF. So you can drop all those `hasRow` and `While(xyz.Read())`. And have simple object getting populated directly. No loop, no risk of typo in `rdr["empid"]`, strong type. And 2 lines of readable codes. – Drag and Drop Sep 16 '20 at 09:22
  • I'll consider that. – pradevan thakur Sep 17 '20 at 12:16