Search code examples
c#json.netgenericsanonymous-types

Use Generics to achieve data in required JSON format


I have a generic class say

public class Generic<T>
{
   public T Data {get; set;}
}

Suppose I have an anonymous object like

var r1 = new {
    A = lstA,
        validation = null as ValidationError
    }

var r2 =  new {
    B = lstB,
        validation = null as ValidationError
    }

And I assigned as below

Generic<object> g1 = new Generic<object>
g1.Data = r1

Generic<object> g2 = new Generic<object>
g2.Data = r2

When I serialize above g1 using JsonSerialize.Serialize (g1), I got output

{
   "Data":{
      "A":[
         {
            
         }
      ],
      "validation":null
   }
}

{
   "Data":{
      "B":[
         {
            
         }
      ],
      "validation":null
   }
}

Right now I achieved above JSON format by assigning anonymous r1 to g1.Data. Is it possible to achieve above JSON format by just using generics?

The name "A" in above JSON format differ in each cases. It can be "A"in one case, "B" in another case etc.

I tried above code and achieved required JSON format using anonymous type and Generics. Would like to know is it possible to achieve above JSON format by usibg generics alone or is there a better way of doing this?


Solution

  • How about to use Dictionary<string, object> dic = new Dictionary<string, object>(); ?

    Generic<object> g1 = new Generic<object>;
    g1.Data = r1
    
    Generic<object> g2 = new Generic<object>;
    g2.Data = r2
    
    dic.Add("A", g1);
    dic.Add("B", g2);