using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class SomeNonSerializableType
public string Value { get; set; }
void OnDeserializing(StreamingContext context) => throw new InvalidOperationException(string.Format("{0} cannot be deserialized.", GetType()));
void OnSerializing(StreamingContext context) => throw new InvalidOperationException(string.Format("{0} cannot be serialized.", GetType()));
public class SomeSerializableType
public string Value { get; set; }
public SomeNonSerializableType Property { get; set; }
public class AutomapperConverter<TModel, TDTO> : JsonConverter
static readonly Lazy<MapperConfiguration> DefaultConfiguration
= new Lazy<MapperConfiguration>(() => new MapperConfiguration(cfg => cfg.CreateMap<TModel, TDTO>().ReverseMap()));
public AutomapperConverter(MapperConfiguration config) => this.config = config ?? throw new ArgumentNullException(nameof(config));
public AutomapperConverter() : this(DefaultConfiguration.Value) { }
readonly MapperConfiguration config;
public override bool CanConvert(Type type) => type == typeof(TModel);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
var dto = config.CreateMapper().Map<TDTO>(value);
serializer.Serialize(writer, dto);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
var dto = serializer.Deserialize<TDTO>(reader);
return config.CreateMapper().Map(dto, dto.GetType(), objectType);
public static void Test()
var someClass = new SomeClass
Property = new SomeNonSerializableType { Value = "hello" },
MapperConfiguration configuration
= new MapperConfiguration(cfg =>
cfg.CreateMap<SomeNonSerializableType, SomeSerializableType>().ReverseMap();
var settings = new JsonSerializerSettings
Converters = { new AutomapperConverter<SomeNonSerializableType, SomeSerializableType>(configuration) },
var json = JsonConvert.SerializeObject(someClass, Formatting.Indented, settings);
var deserialized = JsonConvert.DeserializeObject<SomeClass>(json, settings);
Assert.AreEqual(someClass.Property.Value, deserialized.Property.Value);
Assert.That(() => JsonConvert.SerializeObject(someClass), Throws.Exception);
Assert.That(() => JsonConvert.DeserializeObject<SomeClass>(json), Throws.Exception);
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("{0} version: {1}", typeof(MapperConfiguration).Assembly.GetName().Name, typeof(MapperConfiguration).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];