我正在发出网络请求以将类的某些属性传递给网络 API,因此我按照 method 3 of this post 中的说明进行操作并制作了一个动态契约(Contract)解析器:
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
属性。
我看过this post on 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"
};
关于子类的 C# json 动态契约(Contract)解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28046216/