using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Namespace.Models
public abstract class ModelBase
public class ApplicationLoggingModel : ModelBase
public string Test { get; set; }
public class AnotherModel : ModelBase
public string AnotherTest { get; set; }
public class ModelBaseCollectionDTO
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]
public List<ModelBase> Models { get; set; }
public static void Test()
private static void TestRoundTrip()
var dto = new ModelBaseCollectionDTO
Models = new List<ModelBase>()
new ApplicationLoggingModel { Test = "test value" },
new AnotherModel { AnotherTest = "another test value" },
var json = JsonConvert.SerializeObject(dto, Formatting.Indented, new JsonSerializerSettings { TypeNameAssemblyFormat = FormatterAssemblyStyle.Full });
var dto2 = JsonConvert.DeserializeObject<ModelBaseCollectionDTO>(json);
Assert.IsTrue(dto.Models.Select(m => m.GetType()).SequenceEqual(dto2.Models.Select(m => m.GetType())));
Assert.IsTrue(dto.Models.Select(m => JsonConvert.SerializeObject(m)).SequenceEqual(dto2.Models.Select(m => JsonConvert.SerializeObject(m))));
Console.WriteLine("{0} round-tripped successfully.", dto2);
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
public static void IsTrue(bool value, string message)
throw new AssertionFailedException(message ?? "failed");