返回多个 JSON 作为 HttpResponseMessage
我有一个 HttpResponseMessage
方法,它返回基于数据库数据的 JSON:
public HttpResponseMessage RespMsg(JObject jsonData)
{
HttpResponseMessage response = new HttpResponseMessage();
dynamic json = jsonData;
int recId = jsonData.Id;
var respStructure = myTable.Where(r => r.Id==recId).Select(t => new
{
t.Id,
t.Name
}
var responseJson = JsonConvert.SerializeObject(respStructure);
response.Content = new StringContent(responseJson, null, "application/json");
return response;
}
我得到的响应类似于 {"Id":3,"Name":Third}
。 T1 中的行在表 T2 中有多行 有
var t2Resp = T2.Where(c => c.T1Id == recId);
foreach (var t in t2Resp) {
//call a method that return an object with computed data
}
没有办法将 foreach
中的数据作为单独的 JSON
添加,例如 {"Id":3,"名称":"第三个"} {foreach 中的第一个数据} {foreach 中的第二个数据}
?第一个来自 T1
查询,下一个取决于 t2Resp
长度
I have a HttpResponseMessage
method that returns a JSON based on DB data:
public HttpResponseMessage RespMsg(JObject jsonData)
{
HttpResponseMessage response = new HttpResponseMessage();
dynamic json = jsonData;
int recId = jsonData.Id;
var respStructure = myTable.Where(r => r.Id==recId).Select(t => new
{
t.Id,
t.Name
}
var responseJson = JsonConvert.SerializeObject(respStructure);
response.Content = new StringContent(responseJson, null, "application/json");
return response;
}
The response I get is something like {"Id":3,"Name":Third}
.
The row in T1, has multiple rows in table T2
var t2Resp = T2.Where(c => c.T1Id == recId);
foreach (var t in t2Resp) {
//call a method that return an object with computed data
}
Is there a way to add the data from foreach
as separate JSON
like {"Id":3,"Name":"Third"} {first data from foreach} {second data from foreach}
? The first one is from T1
query and the next ones depending on t2Resp
length
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
提示:- 首先,您必须创建一个与您的响应匹配的 DTO 对象。由于 T1 和 T2 具有一对多关系,因此创建具有以下结构的 DTO 类。
然后,您必须使用此类来填充 T1 和 T2 中的数据,最后将其灭菌为 JSON。如下图所示。
这些代码片段可能会给您一些想法并能够解决这个问题。
快乐编码:)
Hint:- First You have to create a DTO object that matches with your response. Since T1 and T2 have one-to-many relationship create a DTO class with below structure.
Then you have to use this class to populate data from T1 and T2 and finally sterilize to JSON. Something as shown below .
May be theses code snippets give you some idea and able to sort this issue.
Happy coding :)