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.Text.Json.Serialization;
public class OptOutJsonConverterFactory : JsonConverterFactoryDecorator
readonly HashSet<Type> optOutTypes;
public OptOutJsonConverterFactory(JsonConverterFactory innerFactory, params Type [] optOutTypes) : base(innerFactory) => this.optOutTypes = optOutTypes.ToHashSet();
public override bool CanConvert(Type typeToConvert) => base.CanConvert(typeToConvert) && !optOutTypes.Contains(typeToConvert);
public class JsonConverterFactoryDecorator : JsonConverterFactory
readonly JsonConverterFactory innerFactory;
public JsonConverterFactoryDecorator(JsonConverterFactory innerFactory)
if (innerFactory == null)
throw new ArgumentNullException(nameof(innerFactory));
this.innerFactory = innerFactory;
public override bool CanConvert(Type typeToConvert) => innerFactory.CanConvert(typeToConvert);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) => innerFactory.CreateConverter(typeToConvert, options);
public enum SomeEnumNotToSerializeAsAString
public StringEnum StringEnum { get; set; }
public SomeEnumNotToSerializeAsAString SomeEnumNotToSerializeAsAString { get; set; }
public static void Test()
var options = new JsonSerializerOptions
PropertyNameCaseInsensitive = true,
options.Converters.Add(new OptOutJsonConverterFactory(new JsonStringEnumConverter(),
typeof(SomeEnumNotToSerializeAsAString)
StringEnum = StringEnum.Name2,
SomeEnumNotToSerializeAsAString = SomeEnumNotToSerializeAsAString.Value2
var json = JsonSerializer.Serialize(model, options);
Assert.IsTrue(!Enum.GetNames(typeof(SomeEnumNotToSerializeAsAString)).Any(n => json.Contains(n)));
Assert.IsTrue(Enum.GetNames(typeof(StringEnum)).Any(n => json.Contains(n)));
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("System.Text.Json: " + typeof(JsonSerializer).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];