C# json 子 class 的动态合同解析器

C# json dynamic contract resolver for sub class

我正在发出网络请求以将 class 的某些属性传递给网络 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 });

如果属性是基础 class 的一部分,这非常有效,但如果属性是子 class 的一部分,那么它就不会被拾取

因此,例如,该产品有 Option 的子class,而我只想要该选项的 colour 属性。

我查看了 this post on SO,但并不清楚 GetItemTypeNames() 是什么或如何正确使用它,所以想知道是否有人知道我如何更改 DynamicContractResolver 也可以处理子 classes

示例 classes:

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"
};