using System.Collections.Generic;
using System.Diagnostics;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public int Number { get; private set; }
public MyType(int number)
public class MyTypes : IEnumerable<MyType>
private readonly Dictionary<int, MyType> c_index;
public MyTypes(IEnumerable<MyType> seed)
this.c_index = seed.ToDictionary(item => item.Number);
public IEnumerator<MyType> GetEnumerator()
return this.c_index.Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
return this.GetEnumerator();
public int CustomMethod()
public static void Test()
var test = new TestClass();
test.RoundTripWithSettings();
var _myTypes1 = new MyTypes(new[] { new MyType(1), new MyType(2) });
var _jsonContent = JsonConvert.SerializeObject(_myTypes1, Formatting.Indented);
Console.WriteLine("Serialized JSON:" );
Console.WriteLine(_jsonContent);
var _myTypes2 = JsonConvert.DeserializeObject<MyTypes>(_jsonContent);
var _jsonContent2 = JsonConvert.SerializeObject(_myTypes2, Formatting.Indented);
Console.WriteLine("Re-serialized JSON:" );
Console.WriteLine(_jsonContent2);
if (!JToken.DeepEquals(JToken.Parse(_jsonContent), JToken.Parse(_jsonContent2)))
throw new InvalidOperationException("!JToken.DeepEquals(JToken.Parse(_jsonContent), JToken.Parse(_jsonContent2))");
Console.WriteLine("Serialized and re-serialized JSON are identical.");
public void RoundTripWithSettings()
var _myTypes1 = new MyTypes(new[] { new MyType(1), new MyType(2) });
var _serializationSettings = new JsonSerializerSettings
TypeNameHandling = TypeNameHandling.Arrays,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full,
var _jsonContent = JsonConvert.SerializeObject(_myTypes1, Formatting.Indented, _serializationSettings);
Console.WriteLine("Serialized JSON:" );
Console.WriteLine(_jsonContent);
var _myTypes2 = JsonConvert.DeserializeObject<MyTypes>(_jsonContent, _serializationSettings);
var _jsonContent2 = JsonConvert.SerializeObject(_myTypes2, Formatting.Indented, _serializationSettings);
Console.WriteLine("Re-serialized JSON:" );
Console.WriteLine(_jsonContent2);
if (!JToken.DeepEquals(JToken.Parse(_jsonContent), JToken.Parse(_jsonContent2)))
throw new InvalidOperationException("!JToken.DeepEquals(JToken.Parse(_jsonContent), JToken.Parse(_jsonContent2))");
Console.WriteLine("Serialized and re-serialized JSON are identical.");
public static void Main()