NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface> NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface> json json

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>


You don't need to use JsonConverterAttribute, keep your model clean, also use CustomCreationConverter, the code is simpler:

public class SampleConverter : CustomCreationConverter<ISample>{    public override ISample Create(Type objectType)    {        return new Sample();    }}

Then:

var sz = JsonConvert.SerializeObject( sampleGroupInstance );JsonConvert.DeserializeObject<SampleGroup>( sz, new SampleConverter());

Documentation: Deserialize with CustomCreationConverter


It is quite simple and out of the box support provided by json.net, you just have to use the following JsonSettings while serializing and Deserializing:

JsonConvert.SerializeObject(graph,Formatting.None, new JsonSerializerSettings(){    TypeNameHandling =TypeNameHandling.Objects,    TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple});

and for Deserialzing use the below code:

JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bData),type,    new JsonSerializerSettings(){TypeNameHandling = TypeNameHandling.Objects});

Just take a note of the JsonSerializerSettings object initializer, that is important for you.


I solved that problem by using a special setting for JsonSerializerSettings which is called TypeNameHandling.All

TypeNameHandling setting includes type information when serializing JSON and read type information so that the create types are created when deserializing JSON

Serialization:

var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };var text = JsonConvert.SerializeObject(configuration, settings);

Deserialization:

var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };var configuration = JsonConvert.DeserializeObject<YourClass>(json, settings);

The class YourClass might have any kind of base type fields and it will be serialized properly.