【问题标题】:c# Rename a derived property while serializingc#在序列化时重命名派生属性
【发布时间】:2020-04-29 08:51:30
【问题描述】:

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

如果未在派生对象中指定属性,则 Json.Net 修饰不起作用 如果我指定它,我会收到“如果要隐藏,请使用新关键字”的建议。 ,如果我这样做,我可能会失去财产上的基本程序?

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

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    用不同的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:

    virtual 关键字用于修改方法、属性、索引器或 事件声明并允许它在派生中被覆盖 类。

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多