Reputation: 2157
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
Reputation: 34947
You could wrap records
in an anonymous object
return Ok( new {data = records} );
Upvotes: 3
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