I want to serialize an object using json.net and c#. For that i have created a custom contract resolver that extends DefaultContractResolver
class and also i have override the CreateProperties
method. My class is something like
public class Hierarchy{
[JsonProperty("id")]
public int Id{get;set;}
[JsonProperty("parentId")]
public int ParentId{get;set;}
[JsonProperty("nodes")]
public List<Hierarchy> Nodes{get;set;}
}
Now i have an object of this class
{
"id": 3585,
"parentId": 0,
"nodes": [
{
"id": 3586,
"parentId": 3585,
"nodes": [
{
"id": 3587,
"parentId": 3586,
"nodes": null
}
]
},
{
"id": 3599,
"parentId": 3585,
"nodes": [
{
"id": 3600,
"parentId": 3599,
"nodes": null
},
{
"id": 3601,
"parentId": 3599,
"nodes": null
},
{
"id": 3602,
"parentId": 3599,
"nodes": null
},
{
"id": 3603,
"parentId": 3599,
"nodes": null
}
]
},
{
"id": 3744,
"parentId": 3585,
"nodes": null
}
]
}
Now my CustomDefaultResolver class is something like
public class CustomRetrieveResponseResolver : DefaultContractResolver
{
private readonly IList<string> _propertiesToInclude;
public CustomRetrieveResponseResolver(IList<string> propertiesToInclude , Type objType)
{
_propertiesToInclude = propertiesToInclude;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
// some code here
}
}
I'm passing a list of strings to the constructor which has the name of the properties I want to include in the final object. For example if propertiesToInclude = { "id" }
i will get output
{ "id" : 3585 }
Also when propertiesToInclude = { "id" , "nodes" }
i will get the entire object. I know that json.net will bind some contract with Type of object so all the Hierarchy type object will be serializing in the same manner.
So When propertiesToInclude = { "nodes.id" }
is something like this i want an output
{
"nodes" : [
{
"id": 3586
},
{
"id": 3599
},
{
"id": 3744
}
]
}
But I'm getting
{
"nodes" : [
{
"nodes":null
},
{
"nodes":null
},
{
"nodes": null
}
]
}
This means I want to serialize the outer Hierarchy type and the inner Hierarchy type in a different way. I know that CreateProperties
will be going to call only once and that time it will bind some contract or way of serializing Hierarchy Type object and it will use the same contract for every Hierarchy Type object independent of its position in the object.
So is there any way of defining different contracts ( or way of serializing) for the same Type occurring at different hierarchies in the same object?