Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.net does not serialize properties from derived class

Tags:

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?

like image 755
frosty Avatar asked Feb 27 '14 21:02

frosty


People also ask

Does JSON serialize data?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

Which one is correct class for JSON serializer?

The JsonSerializer is a static class in the System. Text. Json namespace. It provides functionality for serializing objects to a JSON string and deserializing from a JSON string to objects.

Can JSON serialize a list?

Json.NET has excellent support for serializing and deserializing collections of objects. To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for.

Can serializable class inherited?

You must explicitly mark each derived class as [Serializable] . If, however, you mean the ISerializable interface, then yes: interface implementations are inherited, but you need to be careful - for example by using a virtual method so that derived classes can contribute their data to the serialization.


1 Answers

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.

like image 51
Brian Rogers Avatar answered Sep 24 '22 14:09

Brian Rogers