I use ContractResolver
in my code:
public class ShouldSerializeContractResolver : DefaultContractResolver
{
List<string> propertyList { get; set; }
public ShouldSerializeContractResolver(List<string> propertyList)
{
this.propertyList = propertyList;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = instance =>
{
if (propertyList.Any())
return propertyList.Contains(property.PropertyName);
return true;
};
return property;
}
}
where propertyList
is a list of required attributes for serialization
What if we have the same classes and attributes in data? For example :
public class Product
{
public int? Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ProductPrice subProductA { get; set; }
public ProductDiscount subProductB { get; set; }
}
public class ProductPrice
{
public int? Id { get; set; }
public string Name { get; set; }
public Amount amount { get; set; }
}
public class ProductDiscount
{
public int? SubId { get; set; }
public string SubName { get; set; }
public Amount amount { get; set; }
}
public class Amount
{
public int? amountId { get; set; }
public string amountName { get; set; }
public Value value { get; set; }
}
public class Value
{
public int? valueId { get; set; }
public string valueName { get; set; }
}
}
I want to serialize Product
class instance and serialize the Product.ProductPrice.Amount.Value.valueId
attribute, but not the Product.ProductDiscount.Amount.Value.valueId
string myResponseBody = JsonConvert.SerializeObject(product, Formatting.Indented, new JsonSerializerSettings { ContractResolver = contractResolver });
return WebOperationContext.Current.CreateTextResponse(myResponseBody,
"application/json; charset=utf-8",
Encoding.UTF8);
Is it possible to do or not? How we can choose required JsonProperty? It is possible to compare DeclaredTypes, but it doesn't work for deep hierarchy.