gpt4 book ai didi

c# - 在 C# 中重写基类的 Json.NET 注解

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:31 29 4
gpt4 key购买 nike

我正在使用一个为 SwaggerDocument 公开模型的公共(public)库。它带有一些通过注释添加的序列化逻辑,以指定在序列化过程中应该忽略什么,以及在序列化和反序列化过程中应该应用什么顺序:

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

最佳答案

这不是一个理想的解决方案,尽管它可行。

您可以使用以下策略来公开基类的一些属性,这些属性会打乱您的自定义派生类中的顺序。

缺点是要声明一些基类的属性,但如您所见,这背后的逻辑非常简单(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"}

关于c# - 在 C# 中重写基类的 Json.NET 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49963452/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com