using System.Collections.Generic;
using Newtonsoft.Json.Converters;
namespace JsonSerialization
public static void Main(string[] args)
var blobItem = new BlobItem();
var dataItemDic = new TypeYDictionary<IEnumerable<IDataItem>>();
var objDic = new Dictionary<string, object> { { "key", "object" } };
dataItemDic.Add("dataItemKey", new List<DataItem>() { new DataItem() { Attributes = objDic } });
blobItem.TypeXDataDictionary.Add("typeXKey", dataItemDic);
var ser = JsonConvert.SerializeObject(blobItem);
Console.WriteLine("Serialized {0}:", blobItem);
var deSerialized = JsonConvert.DeserializeObject<BlobItem>(ser);
Console.WriteLine("Deserialized successfully.");
Console.WriteLine("Re-serialized {0}: ", deSerialized);
Console.WriteLine(JsonConvert.SerializeObject(deSerialized));
public class TypeConverter<T, TSerialized> : CustomCreationConverter<T>
where TSerialized : T, new()
public override T Create(Type objectType)
return new TSerialized();
public class DictionaryValueTypeConverter<TDictionary, TKey, TValue, TValueSerialized> : JsonConverter
where TDictionary : class, IDictionary<TKey, TValue>, new()
where TValueSerialized : TValue
public override bool CanConvert(Type objectType)
throw new NotImplementedException();
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
throw new NotImplementedException();
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
if (reader.TokenType == JsonToken.Null)
var surrogate = serializer.Deserialize<Dictionary<TKey, TValueSerialized>>(reader);
var dictionary = existingValue as TDictionary ?? new TDictionary();
foreach (var pair in surrogate)
dictionary[pair.Key] = pair.Value;
Dictionary<string, IValue> SomeValues { get; set; }
public class Value : IValue
[JsonProperty(ItemConverterType = typeof(TypeConverter<IValue, Value>))]
public Dictionary<string, IValue> SomeValues { get; set; }
public interface ISomeAtrributes
Dictionary<string, object> Attributes { get; set; }
public interface IDataItem : ISomeAtrributes
IValue Value { get; set; }
public class DataItem : IDataItem
[JsonProperty(ItemConverterType = typeof(TypeConverter<IValue, Value>))]
public IValue Value { get; set; }
public Dictionary<string, object> Attributes { get; set; }
public interface IBlobItem
TypeXDictionary<IEnumerable<IDataItem>> TypeXDataDictionary { get; set; }
public class BlobItem : IBlobItem
TypeXDataDictionary = new TypeXDictionary<IEnumerable<IDataItem>>();
[JsonProperty(ItemConverterType = typeof(DictionaryValueTypeConverter<TypeYDictionary<IEnumerable<IDataItem>>, string, IEnumerable<IDataItem>, List<DataItem>>))]
public TypeXDictionary<IEnumerable<IDataItem>> TypeXDataDictionary { get; set; }
public class TypeYDictionary<T> : Dictionary<string, T>
public class TypeXDictionary<T> : Dictionary<string, TypeYDictionary<T>>