JavascriptSerializer serializing property twice when “new” used in subclass

喜欢而已 提交于 2019-12-02 04:39:10

Yes, your assumption is correct. The new keyword is not the same as override; it merely "hides" the base class property, but the original property is still there and can still be discovered via reflection (which is how serializers do their work).

Generally, it is considered a "code smell" to define a method or property in a base class and then replace it with another method or property in a derived class that takes away functionality of the base class. This violates the Liskov Substitution Principle.

Instead of deriving Limited from Full, I would propose that you make an abstract base class for them and put the common stuff in there. Then, you can ADD things to each subclass which are different or exclusive to each (i.e. your differently-typed Status members).

For example:

class Program
{
    static void Main(string[] args)
    {
        System.Web.Script.Serialization.JavaScriptSerializer json = 
            new System.Web.Script.Serialization.JavaScriptSerializer();

        Console.WriteLine(json.Serialize(new Full(true)));
        Console.WriteLine(json.Serialize(new Limited()));
    }
}

public abstract class Base
{
    public String Stuff { get { return "Common things"; } }
}

public class Full : Base
{
    public FullStatus Status { get; set; }

    public Full(bool includestatus)
    {
        if (includestatus)
            Status = new FullStatus();
    }
}

public class Limited : Base
{
    public LimitedStatus Status { get; set; }

    public Limited()
    {
        Status = new LimitedStatus();
    }
}

public class FullStatus
{
    public String Text { get { return "Loads and loads and loads of things"; } }
}

public class LimitedStatus
{
    public String Text { get { return "A few things"; } }
}

Output:

{"Status":{"Text":"Loads and loads and loads of things"},"Stuff":"Common things"}
{"Status":{"Text":"A few things"},"Stuff":"Common things"}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!