3
votes

I noticed that when serializing/deserializing a POCO class with JSON.NET that derives from a base class that uses explicit DataContract attributes then any POCO properties on the derived class are ignored.

For example, in this example, "Address" is not serialized/deserialized:

[DataContract]
public class MyBaseClass
{
    [DataMember(Name = "SomeName")]
    public string Name { get; set; }
}

public class MyDerivedClass : MyBaseClass
{
    public string Address { get; set; }
}

Is that intentional?

FWIW, it does seem that DataContractSerializer (at least the XML one) does the "right thing" here and serializes/deserializes "Address".

Thanks!

Henrik

1
In my testing, the DataContractSerializer will not serialize the subclass at all if it is not decorated with [DataContract]; instead it throws an exception. This seems to be consistent with the documentation for the DataContractAttribute, which states that it is not inherited from the base class.Brian Rogers
@BrianRogers Did you mean the base class needs the attribute? Anyway, it's been a while so maybe it changed. See this documentation for how inheritance affects data contracts.HappyNomad

1 Answers

2
votes

In JSON.NET, at least as of v4.5.6, it detects the DataContract of the base class and assumes opt-in serialization. Since Address is not decorated with the DataMember attribute it does not get serialized.

This is by design according to James Newton-King with no planned change.