覆盖C#中的基类的Json.NET批注

我正在使用公开库的公共图书馆SwaggerDocument。它带有通过注释添加的一些序列化逻辑,以指定序列化期间应忽略的内容以及序列化和反序列化期间应采用的顺序:


    [Newtonsoft.Json.JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 6, PropertyName = "basePath")]

public string BasePath;

我想更改这些批注,而不必使用复制的所有其他逻辑来创建自己的类。我可以扩展此类并覆盖注释吗?例如


MySwaggerDocument: SwaggerDocument 

{

    @override

    [Newtonsoft.Json.JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, Order = 4, PropertyName = "basePath")]

    public string BasePath;

}


FFIVE
浏览 247回答 1
1回答

饮歌长啸

尽管这可行,但这不是理想的解决方案。您可以使用以下策略来暴露基类的某些属性,这些属性会扰乱自定义派生类中的顺序。缺点是声明了一些基类的属性,但是如您所见,其背后的逻辑非常简单(get / set语法为C#7.0)。using Newtonsoft.Json;using System;namespace JsonTest{    public class Base    {        [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 1, PropertyName = "A")]        public string A { get; set; }        [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 2, PropertyName = "X")]        public string X { get; set; }        [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 3, PropertyName = "B")]        public string B { get; set; }    }    public class Derived : Base    {        [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 4, PropertyName = "C")]        public string C { get; set; }        [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 5, PropertyName = "X")]        public new string X        {            get => base.X;            set => base.X = value;        }        [JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 6, PropertyName = "D")]        public string D { get; set; }    }    class Program    {        static void Main(string[] args)        {            Base b = new Base() { A = "a", B = "b", X = "x" };            string serB = JsonConvert.SerializeObject(b);            Console.WriteLine($"Serialized base class:\r\n {serB}");            Derived d = new Derived() { A = "a", B = "b", C = "c", D = "d", X = "x" };            string serD = JsonConvert.SerializeObject(d);            Console.WriteLine($"Serialized derived class:\r\n {serD}");        }    }}输出:Serialized base class: {"A":"a","X":"x","B":"b"}Serialized derived class: {"A":"a","B":"b","C":"c","X":"x","D":"d"}
打开App,查看更多内容
随时随地看视频慕课网APP