According to newtonSoft documents, it's possible to dynamically ignore selected properties by overriding CreateProperties
.
Is it possible to ignore nested properties dynamically?
As an example
public class DynamicContractResolver : DefaultContractResolver
{
private readonly char _startingWithChar;
public DynamicContractResolver(char startingWithChar)
{
_startingWithChar = startingWithChar;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
// only serializer properties that start with the specified character
properties =
properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
return properties;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
And then
Person person = new Person
{
FirstName = "Dennis",
LastName = "Deepwater-Diver"
};
string startingWithF = JsonConvert.SerializeObject(person, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('F') });
Console.WriteLine(startingWithF);
// {
// "FirstName": "Dennis",
// "FullName": "Dennis Deepwater-Diver"
// }
But what if Person
looks like this, and we want do ignore DriverID
?
public class DriverInformation
{
public string DriverID {get;set;}
public string Branch {get;set}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DriverInformation Info {get;set}
public string FullName
{
get { return FirstName + " " + LastName; }
}
}