返回多个JSON作为HttpResponseMessage



我有一个HttpResponseMessage方法,它返回基于DB数据的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
}

有没有一种方法可以像{"Id":3,"Name":"Third"} {first data from foreach} {second data from foreach}一样将foreach中的数据添加为单独的JSON?第一个来自T1查询,下一个取决于t2Resp长度

提示:-首先,您必须创建一个与响应匹配的DTO对象。由于T1和T2具有一对多关系,因此创建具有以下结构的DTO类。

public  class DtoData
{
public string id { get; set; }
public string Name { get; set; }
public List<DaatFromT2> T2Data { get; set; }
}
public class DaatFromT2
{
public string prop1 { get; set; }
public int prop2 { get; set; }
public DateOnly prop3 { get; set; }
}

然后,您必须使用这个类来填充T1和T2中的数据,并最终将其杀菌为JSON。如下所示。

var resposeStructure = new List<DtoData>();
var t1data = myTable.Where(r => r.Id==recId).Select(t => new
{
t.Id,
t.Name
};
var t2Resp = T2.Where(c => c.T2Id == recId);
foreach (var t in t1data)
{
var data = new DtoData
{
id = t.Id,
Name = t.Name,
T2Data = t2Resp.Where(c => t.id == t2Resp.someid)
.Select(t => new
{
//call a method that return an object with computed data
//and map to corresponding properties
});
}
resposeStructure.Append(data);
}
var responseJson = JsonConvert.SerializeObject(respStructure);

这些代码片段可能会给你一些想法,并能够对这个问题进行排序。快乐编码:(

相关内容

  • 没有找到相关文章

最新更新