[英]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. 我正在尝试查询SQL Server,并尝试以JSON格式返回响应。 I am able to get the JSON response like 我可以像这样获得JSON响应
[
{"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);
}
您可以将records
包装在匿名对象中
return Ok( new {data = records} );
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.
然后返回result.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.