OpenStove
OpenStove

Reputation: 734

c# Rename a derived property while serializing

I have a Base Class, with a List as property. I have multiple Classes derived from that one, and I want the having those Property with a different Name while serializing...

The Json.Net decoration doesn't work if the Property is not specified in the Derived Object And if I specify it, I get the advice "Use the new keyword if hiding was intended." , and if I do so, I might lose the base procedures on the 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; };
}

Upvotes: 4

Views: 1068

Answers (1)

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

Override the property in derived class with different json property name.

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.

Upvotes: 4

Related Questions