using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public static void Main()
var item = new MyClass();
item.SomeProperty = "myID";
item.Items = new List<ChildClass>()
item.Items2 = new List<ChildClass2>()
JObject messageWithArray = JObject.FromObject(item);
var settings = new JsonSerializerSettings() { Converters = new List<JsonConverter>() { new DictionaryArrayConverter<ChildClass>(), new DictionaryArrayConverter<ChildClass2>() } };
var serializer = JsonSerializer.CreateDefault(settings);
var messageWithDictionary = JObject.FromObject(item, serializer);
Console.WriteLine(messageWithArray);
Console.WriteLine(messageWithDictionary);
var arrayMessageToObject = JObject.Parse(messageWithArray.ToString()).ToObject<MyClass>();
Console.WriteLine("**" + arrayMessageToObject.Items.First().cc1IDProperty + "**");
var dictMessageToObject = JObject.Parse(messageWithDictionary.ToString()).ToObject<MyClass>(serializer);
Console.WriteLine("**" + dictMessageToObject.Items.First().cc1IDProperty + "**");
Console.WriteLine("Failed with unhandled exception: ");
public string SomeProperty { get; set; }
public List<ChildClass> Items { get; set; }
public List<ChildClass2> Items2 { get; set; }
public string cc1IDProperty { get; set; }
public string SomeOtherProperty { get; set; }
public string cc2IDProperty { get; set; }
public string AnotherProperty { get; set; }
class DictionaryArrayConverter<T> : JsonConverter
public override bool CanConvert(Type objectType)
return typeof(List<T>).IsAssignableFrom(objectType);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
var jObj = JObject.Load(reader);
var jDict = jObj.ToObject<Dictionary<string, T>>();
return jDict.Values.ToList();
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
List<T> castObject = (List<T>)value;
Dictionary<string, T> castDict = new Dictionary<string, T>();
foreach (dynamic item in castObject)
castDict.Add(item.cc1IDProperty, item);
else if(item is ChildClass2)
castDict.Add(item.cc2IDProperty, item);
serializer.Serialize(writer, castDict);