gpt4 book ai didi

c#在序列化时重命名派生属性

转载 作者:行者123 更新时间:2023-12-03 19:13:06 24 4
gpt4 key购买 nike

我有一个基类,一个 List 作为属性。
我有多个从那个类派生的类,我希望在序列化时具有不同名称的这些属性......

如果派生对象中未指定属性,则 Json.Net 装饰不起作用
如果我指定它,我会得到建议“如果打算隐藏,则使用新关键字”。 ,如果我这样做,我可能会失去属性(property)的基本程序?

public class Translation
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; };

[JsonProperty(PropertyName = "translatedCaption")]
public string TranslatedCaption { get; set; };

public List<Translation> Children { get; set; };

public Translation(string name,string translatedCaption)
{
Name=name;
TranslatedCaption=translatedCaption;
Children = new List<Translation>();
}

public void Add(Translation translation)
{
...
}
}
public class Translation_Model : Translation
{
[JsonProperty(PropertyName = "tables")]
public List<Translation> Children { get; set; };
}

最佳答案

使用不同的 json 属性名称覆盖派生类中的属性。

public class Translation
{
...
public virtual List<Translation> Children { get; set; }
...
}

public class Translation_Model : Translation
{
...
[JsonProperty(PropertyName = "tables")]
public override List<Translation> Children { get; set; }
...
}

From MSDN:

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.

关于c#在序列化时重命名派生属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61497766/

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