public void CustomParserAndSerializer() { var dictionary = new Dictionary <int, int>(); for (int i = 0; i < 8; ++i) { dictionary.Add(i, i); } var factory = new DictionaryJsonConverterFactoryBuilder() .Add(s => ~int.Parse(s), i => (~i).ToString()) .Build(); var options = new JsonSerializerOptions(); options.Converters.Add(factory); // Verify that these custom tools are necessary! Assert.Throws <NotSupportedException>(() => JsonSerializer.Serialize(dictionary)); var serialized = JsonSerializer.Serialize(dictionary, options); var deserialized = JsonSerializer.Deserialize <Dictionary <int, int> >(serialized, options); Assert.Equal(dictionary, deserialized); }
static async Task Main2(string[] args) { var semaphore = new SemaphoreSlim(1); // using (await AutoSemaphore.WaitAsync(semaphore)); // using new Disposable<string>("Farewell", Console.WriteLine); // using var disposable = Disposable.Create("Goodbye", Console.WriteLine); var dictionary = new Dictionary <Guid, string>(); for (int i = 0; i < 8; ++i) { var c = (char)('a' + i); dictionary.Add(Guid.NewGuid(), new string(c, 8)); } var options = new JsonSerializerOptions { WriteIndented = true }; var intConverter = (JsonConverter <int>)options.GetConverter(typeof(int)); var types = new Type[] { typeof(int), typeof(long), typeof(decimal), typeof(string), typeof(DateTime) }; foreach (var type in types) { var converter = options.GetConverter(type); Console.WriteLine($"{type} -- {converter}"); } var builder = new DictionaryJsonConverterFactoryBuilder(); options.Converters.Add(DictionaryJsonConverterFactory.Default); var d = JsonSerializer.Deserialize <ImmutableSortedDictionary <Guid, int> >("{\"49fc2162-744a-4a42-b685-ea1e30ce2a2f\": 99}", options); var json = JsonSerializer.Serialize(Guid.NewGuid(), options); Console.WriteLine(json); var bytes = await File.ReadAllBytesAsync("input.json"); var data = JsonSerializer.Deserialize <Dictionary <Guid, SortedDictionary <Guid, int> > >(bytes, options); Console.WriteLine("Parse successful!"); Console.WriteLine(JsonSerializer.Serialize(data, options)); }
public void CustomParserAndSerializer() { var dictionary = new Dictionary <int, int>(); for (int i = 0; i < 8; ++i) { dictionary.Add(i, i); } var factory = new DictionaryJsonConverterFactoryBuilder() .Add(s => ~int.Parse(s), i => (~i).ToString()) .Build(); var options = new JsonSerializerOptions(); options.Converters.Add(factory); var serialized = JsonSerializer.Serialize(dictionary, options); var deserialized = JsonSerializer.Deserialize <Dictionary <int, int> >(serialized, options); Assert.Equal(dictionary, deserialized); }