I have a class with multiple properties where some of the properties is a complex type those it self having multiple other properties, I don't want to use JsonIgnore
annotation over all those unwanted properties, looking way to get only one property to serialize from some complex type.
For example I have 3 classes
class Organization
{
public Int32 ID {get; set;}
public string Name {get; set;}
public Geography Location {get; set;}
public Employee AreaHead {get; set;}
}
class Geography
{
public Int32 GeoID {get; set;}
public string Country {get; set;}
public string City {get; set;}
public string State {get; set;}
}
class Employee
{
public Int32 EmpID {get; set;}
public string Name {get; set;}
public DateTime DOB {get; set;}
public string Gender {get; set;}
}
here I want to serialize the Organization
class object, that should include only 'Country' from Geography and 'EmpID' from Employee for respective Location and AreaHead properties, the json string output I am expecting as below using JsonConvert.SerializeObject
method from NewtonSoft library.
{
"ID":1,
"Name":"Sales",
"Location":"India",
"AreaHead":5464
}
is this possible using DefaultContractResolver?
ContractResolver
public class DynamicContractResolver : DefaultContractResolver
{
private readonly InfoProperty[] _jasonProperies;
public DynamicContractResolver(params InfoProperty[] includePropertyForSerilization)
{
_jasonProperies = includePropertyForSerilization;
}
protected override JsonContract CreateContract(Type objectType)
{
if (typeof(TFDisplay).IsAssignableFrom(objectType))
{
var contract = this.CreateObjectContract(objectType);
contract.Converter = null; // Also null out the converter to prevent infinite recursion.
return contract;
}
return base.CreateContract(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
if (_jasonProperies != null && _jasonProperies.Length > 0)
{
if (_jasonProperies.Any(o => (o.PropertyContainer ?? type) == type))
{
properties = properties.Where(p => _jasonProperies.Any(o => (o.PropertyContainer ?? type) == type && o.PropertyName == p.PropertyName)).ToList();
}
}
return properties;
}
public class InfoProperty
{
public InfoProperty(string propertyName)
{
this.PropertyName = propertyName;
}
public InfoProperty() { }
public InfoProperty(Type propertyContainer, string propertyName)
{
this.PropertyContainer = propertyContainer;
this.PropertyName = propertyName;
}
public Type PropertyContainer { get; set; }
public string PropertyName { get; set; }
}
}