skip to Main Content

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?

2

Answers


  1. I don’t think you need to use generics. It sounds like you just want the property name to be the same, whether it’s A, B or Elephant for that particular property (and others).

    If you have to use dynamic objects then look at creating a custom contract resolver that can rename the property: https://www.newtonsoft.com/json/help/html/contractresolver.htm

    Alternatively, you can just use the [JsonProperty(PropertyName = "YourName")] attribute from Newtonsoft.Json. Here’s an example:

    internal class SomethingA
    {
        [JsonProperty(PropertyName = "C")]
        public IList<int> A { get; set; }
    }
    
    internal class SomethingB
    {
        [JsonProperty(PropertyName = "C")]
        public IList<int> B { get; set; }
    }
    
    internal class Program
    {
        static void Main(string[] args)
        {
            var somethingA = new SomethingA { A = new List<int> { 1, 2 } };
            var somethingB = new SomethingB { B = new List<int> { 3, 4 } };
    
            var aSerialized = JsonConvert.SerializeObject(somethingA); // gives {"C":[1,2]}
            var bSerialized = JsonConvert.SerializeObject(somethingB); // gives {"C":[3,4]}
        }
    }
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search