20
votes

I'm using JSON.NET 6.0.1. When I use the SerializeObject method to serialize an object of my derived class, it serializes properties from base class only. Here is the code snippet:

string v = JsonConvert.SerializeObject(
                service, 
                Formatting.Indented, 
                new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.All
                });

base class:

[DataContract]
public abstract partial class DataEntity : IDataEntity, INotifyPropertyChanging, INotifyPropertyChanged
{
    ...
}

derived class:

[Table(Name = "dbo.mytable")]
public sealed class mytable : DataEntity
{
    ...
}

Am I missing something?

3

3 Answers

28
votes

Yes, you are missing the [DataContract] attribute on the derived class. You also need to add [DataMember] to any properties or fields that you want serialized, if you haven't already added them. Json.Net was changed in version 5.0 release 1 (April 2013) such that the [DataContract] attribute is not inherited.

Note that if you remove all instances of [DataContract] and [DataMemeber] from your classes, Json.Net behaves differently: in that case, the default behavior is for Json.Net to serialize all public properties, both in the base and derived classes.

4
votes

Adding the attribute [JsonObject(MemberSerialization.OptOut)] to your derived class will include all its public members to be serialized.

[Table(Name = "dbo.mytable")]
[JsonObject(MemberSerialization.OptOut)]
public sealed class mytable : DataEntity
{
    ...
}

Alternatively, if you only want certain properties of your derived class to be serialized you can add the attribute [JsonProperty] to each one (This would be equivalent of adding [DataMember] to each property along with [DataContract] on the class).

-2
votes

JsonConvert.SerializeObject was only return {} for me. I found that I needed to add a new constructor to the class before it serialized properly.