CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
using AutoMapper;
//https://stackoverflow.com/questions/63380271/newtonsoft-json-auto-map-specific-properties
public class SomeNonSerializableType
{
public string Value { get; set; }
// Trick to generate errors serializing SomeNonSerializableType
[OnDeserializing]
void OnDeserializing(StreamingContext context) => throw new InvalidOperationException(string.Format("{0} cannot be deserialized.", GetType()));
[OnSerializing]
void OnSerializing(StreamingContext context) => throw new InvalidOperationException(string.Format("{0} cannot be serialized.", GetType()));
}
public class SomeSerializableType
{
public string Value { get; set; }
}
public class SomeClass
{
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);
}
}
class TestClass
{
public static void Test()
{
var someClass = new SomeClass
{
Property = new SomeNonSerializableType { Value = "hello" },
};
// Configure this statically on startup
MapperConfiguration configuration
= new MapperConfiguration(cfg =>
{
// Add all your mapping configurations here.
// ReverseMap() ensures you can map from and to the DTO
cfg.CreateMap<SomeNonSerializableType, SomeSerializableType>().ReverseMap();
});
// Set up settings using the global configuration.
var settings = new JsonSerializerSettings
{
Converters = { new AutomapperConverter<SomeNonSerializableType, SomeSerializableType>(configuration) },
};
var json = JsonConvert.SerializeObject(someClass, Formatting.Indented, settings);
Console.WriteLine(json);
var deserialized = JsonConvert.DeserializeObject<SomeClass>(json, settings);
Assert.AreEqual(someClass.Property.Value, deserialized.Property.Value);
// Assert that SomeNonSerializableType really isn't serializable, so we know it's getting replaced properly.
Assert.That(() => JsonConvert.SerializeObject(someClass), Throws.Exception);
Assert.That(() => JsonConvert.DeserializeObject<SomeClass>(json), Throws.Exception);
}
}
public class Program
{
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();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
public static string GetNetCoreVersion()
{
//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
//
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];
return null;
}
}