I want to serialize objects using json.net and C# .Also I want only selected properties to be inside the final JSON object returned. I have two classes
public class Class {
[JsonProperty("className")]
public string Name{ get; set;}
[JsonProperty("tierUnitId")]
public int? TierUnitId { get; set; }
[JsonProperty("options")]
public List<Options> Options{get; set;}
}
public class Options{
[JsonProperty("idNum")]
public int? idNum {get; set;}
[JsonProperty("options")]
public string Options {get; set;}
}
Now I have an Class object which I want to serialize
.
{
"className" : "Class",
"tierUnitId" : 101,
"options" : [
{ "idNum" : 10 , "options" : "00010011" } ,
{ "idNum" : 11 , "options" : "11110011" }
]
}
For that i have override the CreateProperties
method of the DefaultContractResolver
class for including only selected properties.Also i'm passing the list of properties to be included to the constructor of my CustomRetrieveResponseResolver
class which is extending DefaultContractResolver
.
private readonly IList<string> _propertiesToInclude;
public CustomRetrieveResponseResolver(IList<string> propertiesToInclude)
{
_propertiesToInclude = propertiesToInclude;
}
I have a list of strings propertiesToInclude
which have the name of properties to be included.
For ex:
propertiesToInclude = { "Name" , "options.idNum" }
Now the problem is that in the list propertiesToInclude
i have the relative names of the nested properties. I know that CreateProperties
is going to be called twice one for Class
and then for options
Class ( due to the List<Options> Options
inside Class ). Is there any way of serializing in this manner ? Like the output for the above object will be
{
"className" : "Class",
"options" : [
{ "idNum" : 10 } ,
{ "idNum" : 11 }
]
}
Can Someone help me in this i.e serializing selected values with the using path of nested properties?