我正在发出一个web请求,将类的某些属性传递给Web api,所以我按照本文方法3中的说明做了一个动态合约解析器:
public class DynamicContractResolver : DefaultContractResolver
{
private IList<string> _propertiesToSerialize = null;
public DynamicContractResolver(IList<string> propertiesToSerialize)
{
_propertiesToSerialize = propertiesToSerialize;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.Where(p => _propertiesToSerialize.Contains(p.PropertyName)).ToList();
}
}
示例用法:
var propsToSerialise = new List<string>()
{
"body_html",
"product_type",
"published_scope",
"title",
"vendor",
"handle"
};
DynamicContractResolver contractResolver = new DynamicContractResolver(propsToSerialise);
string json = JsonConvert.SerializeObject(product, Formatting.None, new JsonSerializerSettings { ContractResolver = contractResolver });
如果属性是基类的一部分,这非常有效,但如果属性是子类的一部分,那么它不会被拾取
例如,产品有一个子类 Option
,我只需要该选项的 colour
属性。
我在SO上看了这篇文章,但不太清楚GetItemTypeNames()
是什么或如何正确使用它,所以想知道是否有人知道如何更改DynamicContractResolver
来处理子类
示例类:
public class Product
{
public string body_html { get; set; }
public DateTime created_at { get; set; }
public string handle { get; set; }
public int id { get; set; }
public string product_type { get; set; }
public DateTime published_at { get; set; }
public string published_scope { get; set; }
public string tags { get; set; }
public string template_suffix { get; set; }
public string title { get; set; }
public ProductVariant[] variants { get; set; }
public string vendor { get; set; }
public Option option { get; set; }
}
public class Option
{
public string colour { get; set; } // this is the property I want to serialise
public string size { get; set; }
public string notes { get; set; }
}
我已经通过将CreateProperties
覆盖更改为:
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.Where(p => _propertiesToSerialize.Contains(string.Format("{0}.{1}", p.DeclaringType.Name, p.PropertyName))).ToList();
}
然后我可以将我的propsToSerialise
变量更改为
var propsToSerialise = new List<string>()
{
"Product.body_html",
"Product.product_type",
"Product.published_scope",
"Product.title",
"Product.vendor",
"Product.handle",
"Product.option",
"Options.colour"
};