Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing POCO class derived from baseclass with DataContract?

Tags:

json.net

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

like image 643
Henrik Frystyk Nielsen Avatar asked Dec 05 '25 13:12

Henrik Frystyk Nielsen


1 Answers

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.

like image 64
Nicknow Avatar answered Dec 09 '25 20:12

Nicknow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!