Example #1
0
        public static void Run()
        {
            string jsonString;

            WeatherForecastWithEnumDictionary weatherForecast =
                WeatherForecastFactories.CreateWeatherForecastWithEnumDictionary();

            // <Register>
            var serializeOptions = new JsonSerializerOptions();

            serializeOptions.Converters.Add(new DictionaryTKeyEnumTValueConverter());
            // </Register>
            serializeOptions.WriteIndented = true;
            jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            // <Deserialize>
            var deserializeOptions = new JsonSerializerOptions
            {
                Converters =
                {
                    new DictionaryTKeyEnumTValueConverter()
                }
            };

            weatherForecast = JsonSerializer.Deserialize <WeatherForecastWithEnumDictionary>(
                jsonString, deserializeOptions);
            // </Deserialize>
            weatherForecast.DisplayPropertyValues();
        }
Example #2
0
        static void Main(string[] args)
        {
            var serializeOptions = new JsonSerializerOptions();

            serializeOptions.Converters.Add(new DictionaryTKeyEnumTValueConverter());

            var o = new WeatherForecastWithEnumDictionary
            {
                Date               = DateTimeOffset.Now,
                Summary            = "summary",
                TemperatureCelsius = 15,
                TemperatureRanges  = new Dictionary <SummaryWordsEnum, int>
                {
                    { SummaryWordsEnum.Cold, 0 },
                    { SummaryWordsEnum.Hot, 100 }
                }
            };

            var serializedObject = JsonSerializer.Serialize(o, serializeOptions);

            Debug.WriteLine($"{serializedObject}");

            var o2 = JsonSerializer.Deserialize <WeatherForecastWithEnumDictionary>(serializedObject, serializeOptions);

            Debug.WriteLine($"{o2.TemperatureCelsius}");
        }
Example #3
0
 public static void DisplayPropertyValues(this WeatherForecastWithEnumDictionary wf)
 {
     Utilities.DisplayPropertyValues(wf);
     Console.Write($"TemperatureRanges:\n");
     foreach (KeyValuePair <SummaryWordsEnum, int> kvp in wf.TemperatureRanges)
     {
         Console.Write($"  {kvp.Key.ToString()}, {kvp.Value}\n");
     }
     Console.WriteLine();
 }
Example #4
0
 public static WeatherForecastWithEnumDictionary CreateWeatherForecastWithEnumDictionary()
 {
     var weatherForecast = new WeatherForecastWithEnumDictionary
     {
         Date = DateTime.Parse("2019-08-01"),
         TemperatureCelsius = 25,
         Summary = "Hot",
         TemperatureRanges = new Dictionary<SummaryWordsEnum, int> { { SummaryWordsEnum.Cold, 20 }, { SummaryWordsEnum.Hot, 40 } }
     };
     return weatherForecast;
 }