trx
trx

Reputation: 2157

Return JSON as response from the Web API

I am trying to query the SQL server and trying to return the response in the JSON format. I am able to get the JSON response like

[
  {"R_ID":"368203","ROOM":"K2"}, 
  {"R_ID":"368203","ROOM":"K2"}
]

But I want the response to be wrapped inside the data like

{
  "data": [
    {"R_ID":"368203","ROOM":"K2"}, 
    {"R_ID":"368203","ROOM":"K2"}
   ]
}

So now I changed my model class like

public class DatabaseResult
{
  public int r_id { get; set; }
  public string room { get; set; }
}

public class RootObject
{
  public List<DatabaseResult> data { get; set; }
}

I am not sure how would I change the controller to get the response as expected

connection.Open();
List<DatabaseResult> records = new List<DatabaseResult>();
using (var reader = command.ExecuteReader())
{
  while (reader.Read())
  {
    var row = new DatabaseResult
    {
      request_id = (int)reader["request_id"],
      room = (string)reader["room"],
    };
    records.Add(row);
  }
  return Ok(records);
}

Upvotes: 0

Views: 184

Answers (2)

tmaj
tmaj

Reputation: 34947

You could wrap records in an anonymous object

 return Ok( new {data = records} );

Upvotes: 3

Sajeetharan
Sajeetharan

Reputation: 222522

You need to create the same Model in your backend, and populate like,

RootObject result = new RootObject();


 while (reader.Read())
 {
   var row = new DatabaseResult
   {
      request_id = (int)reader["request_id"],
      room = (string)reader["room"],
   };
   records.Add(row);
 }
 result.data = records;

then return the result.

Upvotes: 1

Related Questions