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?
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With