JSON序列化中类属性的相同名称

时间:2018-05-28 16:36:07

标签: c# serialization attributes json.net

我在代码中使用ContractResolver

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

其中propertyList是序列化所需属性的列表

如果我们在数据中有相同的类和属性怎么办?例如:

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

我想序列化Product类实例并序列化Product.ProductPrice.Amount.Value.valueId属性,但不是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);

有可能做到吗?我们如何选择所需的JsonProperty?可以比较DeclaredTypes,但它不适用于深层次结构。

0 个答案:

没有答案