Search code examples
c#jsonhttpresponsemessage

Return multiple JSON as HttpResponseMessage


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


Solution

  • 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.

     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; }
    }
    

    Then you have to use this class to populate data from T1 and T2 and finally sterilize to JSON. Something as shown below .

        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);
    

    May be theses code snippets give you some idea and able to sort this issue. Happy coding :)