Search code examples
c#inheritancejson-serialization

Serialize to JSON a class that hides member of base class


There are two classes:

class Document {
    public DocumentItem[] DocumentItemList { get; set; }
}

class DocumentViewModel : Document{
    public new DocumentItemViewModel[] DocumentItemList { get; set; }
}

DocumentItemList in derived class hides DocumentItemList in base class.

When DocumentViewModel object is serialized to JSON:

DocumentViewModel instance = CreateObject(); // object gets created
string serializedContent = new JavaScriptSerializer().Serialize(instance);

there are two DocumentItemLists in serialized string:

{
    "DocumentItemList": [{
            ... etc. ...
    }],
    "DocumentItemList": null
}

Why is it like that? This causes error, when data is deserialized.

(BTW, I tested serialization with Newtonsoft.JSON, and that serializer doesn't have this error).


Solution

  • In case you want to stick with JavaScriptSerializer, you may consider to use [JsonIgnore] attribute, on the property you want to be ignored, this is discussed about the shadowed properties in a thread here.

    Here you go:

    class Document {
        public DocumentItem[] DocumentItemList { get; set; }
    }
    
    class DocumentViewModel : Document{
        [JsonIgnore]
        public new DocumentItemViewModel[] DocumentItemList { get; set; }
    }