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;
using JToken = Newtonsoft.Json.Linq.JToken;
class CustomStringToRoleConverter : JsonConverter<ISet<User.Role>> {
public override ISet<User.Role> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
JsonSerializer.Deserialize<List<string>>(ref reader, options)
.Select(s => Enum.Parse<User.Role>(s))
public override void Write(Utf8JsonWriter writer, ISet<User.Role> roles, JsonSerializerOptions options) =>
JsonSerializer.Serialize(writer, roles.Select(r => r.ToString()), options);
public ISet<User.Role> Roles { get; set; } = new HashSet<User.Role>();
public static void Test()
var options = new JsonSerializerOptions
Converters = { new CustomStringToRoleConverter() },
var model = JsonSerializer.Deserialize<User>(json, options);
var json2 = JsonSerializer.Serialize(model, options);
Console.WriteLine("Re-serialized {0}", model);
Console.WriteLine(json2);
Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(json2)));
static string GetJson() => @"{""Roles"":[""Admin"",""User""]}";
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("System.Text.Json version: " + 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.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];