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
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:How about to use
Dictionary<string, object> dic = new Dictionary<string, object>();
?