C#json动态合约解析器为子类

时间:2015-01-20 13:11:36

标签: c# json serialization json.net

我正在制作一个webrequest,将类的某些属性传递给web api,所以我按照method 3 of this post中的说明制作了动态合约解析器:

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()是什么或如何正确使用它所以想知道是否有人知道如何更改{{ 1}}也处理子类

示例类:

DynamicContractResolver

1 个答案:

答案 0 :(得分:2)

我已将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"
};