コード例 #1
0
        public static void Run()
        {
            var weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            byte[] jsonUtf8Bytes;
            var    options = new JsonSerializerOptions
            {
                WriteIndented = true
            };

            jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(weatherForecast, options);
            // </SnippetSerialize>
            Console.WriteLine($"JSON output:\n{Encoding.UTF8.GetString(jsonUtf8Bytes)}\n");

            // <SnippetDeserialize1>
            var readOnlySpan = new ReadOnlySpan <byte>(jsonUtf8Bytes);

            weatherForecast = JsonSerializer.Deserialize <WeatherForecast>(readOnlySpan);
            // </SnippetDeserialize1>
            weatherForecast.DisplayPropertyValues();

            // <SnippetDeserialize2>
            var utf8Reader = new Utf8JsonReader(jsonUtf8Bytes);

            weatherForecast = JsonSerializer.Deserialize <WeatherForecast>(ref utf8Reader);
            // </SnippetDeserialize2>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #2
0
        public static void Run()
        {
            string jsonString;
            var wf = WeatherForecastFactories.CreateWeatherForecast();

            var options = new JsonSerializerOptions();
            options.WriteIndented = true;
            options.Converters.Add(new WeatherForecastRequiredPropertyConverter());
            jsonString = JsonSerializer.Serialize(wf, options);
            Console.WriteLine($"JSON with Date:\n{jsonString}\n");

            wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, options);
            wf.DisplayPropertyValues();

            jsonString = @"{""TemperatureCelsius"": 25,""Summary"":""Hot""}";
            Console.WriteLine($"JSON without Date:\n{jsonString}\n");

            // The missing-date JSON deserializes without error if the converter isn't used.
            Console.WriteLine("Deserialize without converter");
            wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString);
            wf.DisplayPropertyValues();

            Console.WriteLine("Deserialize with converter");
            try
            {
                wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, options);
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"Exception thrown: {ex.Message}\n");
            }
            // wf object is unchanged if exception is thrown.
            wf.DisplayPropertyValues();
        }
コード例 #3
0
        public static void Run()
        {
            string jsonString;
            var    wf = WeatherForecastFactories.CreateWeatherForecast();

            var options = new JsonSerializerOptions();

            options.WriteIndented = true;
            options.Converters.Add(new DateTimeOffsetNullHandlingConverter());
            jsonString = JsonSerializer.Serialize(wf, options);
            Console.WriteLine($"JSON with valid Date:\n{jsonString}\n");

            wf = JsonSerializer.Deserialize <WeatherForecast>(jsonString, options);
            wf.DisplayPropertyValues();

            jsonString = @"{""Date"": null,""TemperatureCelsius"": 25,""Summary"":""Hot""}";
            Console.WriteLine($"JSON with null Date:\n{jsonString}\n");

            // The null-date JSON deserializes with error if the converter isn't used.
            try
            {
                wf = JsonSerializer.Deserialize <WeatherForecast>(jsonString);
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"Exception thrown: {ex.Message}\n");
            }

            Console.WriteLine("Deserialize with converter");
            wf = JsonSerializer.Deserialize <WeatherForecast>(jsonString, options);
            wf.DisplayPropertyValues();
        }
コード例 #4
0
        public static void Run()
        {
            string          jsonString;
            WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.DisplayPropertyValues();

            // <Serialize>
            var serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true,
                Converters    =
                {
                    new DateTimeOffsetConverter()
                }
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);
            // </Serialize>
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            // <Deserialize>
            var deserializeOptions = new JsonSerializerOptions();

            deserializeOptions.Converters.Add(new DateTimeOffsetConverter());
            weatherForecast = JsonSerializer.Deserialize <WeatherForecast>(jsonString, deserializeOptions);
            // </Deserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #5
0
        public static void Run()
        {
            string jsonString;

            var weatherForecast = WeatherForecastFactories.CreateWeatherForecastWithEnumDictionary();

            // <Register>
            var serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true,
                Converters    =
                {
                    new DictionaryTKeyEnumTValueConverter()
                }
            };

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

            // <Deserialize>
            var deserializeOptions = new JsonSerializerOptions();

            deserializeOptions.Converters.Add(new DictionaryTKeyEnumTValueConverter());
            weatherForecast = JsonSerializer.Deserialize <WeatherForecastWithEnumDictionary>(jsonString, deserializeOptions);
            // </Deserialize>
            weatherForecast !.DisplayPropertyValues();
        }
コード例 #6
0
        public static void Run()
        {
            string          jsonString;
            WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = new UpperCaseNamingPolicy(),
                WriteIndented        = true
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </SnippetSerialize>
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            // <SnippetDeserialize>
            options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = new UpperCaseNamingPolicy()
            };
            weatherForecast = JsonSerializer.Deserialize <WeatherForecast>(jsonString, options);
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #7
0
        public static void Run()
        {
            string jsonString;
            WeatherForecastWithEnum weatherForecast = WeatherForecastFactories.CreateWeatherForecastWithEnum();

            weatherForecast.DisplayPropertyValues();

            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            Console.WriteLine($"JSON with enum as number:\n{jsonString}\n");

            // <SnippetSerialize>
            options = new JsonSerializerOptions();
            options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
            options.WriteIndented = true;
            jsonString            = JsonSerializer.Serialize(weatherForecast, options);
            // </SnippetSerialize>
            Console.WriteLine($"JSON with enum as string:\n{jsonString}\n");

            // <SnippetDeserialize>
            options = new JsonSerializerOptions();
            options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
            weatherForecast = JsonSerializer.Deserialize <WeatherForecastWithEnum>(jsonString, options);
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #8
0
        public static void Run()
        {
            string jsonString;
            var    wf = WeatherForecastFactories.CreateWeatherForecastAttrReg();

            var options = new JsonSerializerOptions
            {
                WriteIndented = true
            };

            jsonString = JsonSerializer.Serialize(wf, options);
            Console.WriteLine($"JSON with Date:\n{jsonString}\n");

            wf = JsonSerializer.Deserialize <WeatherForecastWithRequiredPropertyConverterAttribute>(jsonString, options);
            wf.DisplayPropertyValues();

            jsonString = @"{""TemperatureCelsius"": 25,""Summary"":""Hot""}";
            Console.WriteLine($"JSON without Date:\n{jsonString}\n");

            Console.WriteLine("Deserialize with converter");
            try
            {
                wf = JsonSerializer.Deserialize <WeatherForecastWithRequiredPropertyConverterAttribute>(jsonString, options);
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"Exception thrown: {ex.Message}\n");
            }
            // wf object is unchanged if exception is thrown.
            wf.DisplayPropertyValues();
        }
コード例 #9
0
        public static void Run()
        {
            var weatherForecast = WeatherForecastFactories.CreateWeatherForecastWithPOCOs();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            string jsonString;

            jsonString = JsonSerializer.Serialize(weatherForecast);
            // </SnippetSerialize>

            // <SnippetSerializeWithGenericParameter>
            jsonString = JsonSerializer.Serialize <WeatherForecastWithPOCOs>(weatherForecast);
            // </SnippetSerializeWithGenericParameter>

            Console.WriteLine($"JSON output:\n{jsonString}\n");

            // <SnippetSerializePrettyPrint>
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </SnippetSerializePrettyPrint>
            Console.WriteLine($"Pretty-printed JSON output:\n{jsonString}\n");

            // <SnippetDeserialize>
            weatherForecast = JsonSerializer.Deserialize <WeatherForecastWithPOCOs>(jsonString);
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #10
0
        public static void Run()
        {
            string jsonString;
            var    wf = WeatherForecastFactories.CreateWeatherForecast();

            wf.DisplayPropertyValues();

            var serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true,
                Converters    =
                {
                    new WeatherForecastRuntimeIgnoreConverter()
                }
            };

            jsonString = JsonSerializer.Serialize(wf, serializeOptions);
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            wf.Summary = "N/A";
            wf.DisplayPropertyValues();
            jsonString = JsonSerializer.Serialize(wf, serializeOptions);
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            var deserializeOptions = new JsonSerializerOptions
            {
                Converters =
                {
                    new WeatherForecastRuntimeIgnoreConverter()
                }
            };

            wf = JsonSerializer.Deserialize <WeatherForecast>(jsonString, deserializeOptions);
            wf.DisplayPropertyValues();
        }
コード例 #11
0
        public static void Run()
        {
            string jsonString;
            var    wf = WeatherForecastFactories.CreateWeatherForecast();

            wf.DisplayPropertyValues();

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

            serializeOptions.Converters.Add(new WeatherForecastCallbacksConverter());
            serializeOptions.WriteIndented = true;
            jsonString = JsonSerializer.Serialize(wf, serializeOptions);
            // </SnippetSerialize>

            Console.WriteLine($"JSON output:\n{jsonString}\n");

            // <SnippetDeserialize>
            var deserializeOptions = new JsonSerializerOptions();

            deserializeOptions.Converters.Add(new WeatherForecastCallbacksConverter());
            wf = JsonSerializer.Deserialize <WeatherForecast>(jsonString, deserializeOptions);
            // <SnippetDeserialize>

            wf.DisplayPropertyValues();
        }
コード例 #12
0
        public static void Run()
        {
            string jsonString;

            // Serialize to create input JSON
            var weatherForecast  = WeatherForecastFactories.CreateWeatherForecast();
            var serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true
            };

            serializeOptions.WriteIndented = true;
            jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);
            Console.WriteLine($"JSON input:\n{jsonString}\n");

            // Deserialize without converter
            // Properties are JsonElement type.
            WeatherForecastWithObjectProperties weatherForecastWithObjectProperties = JsonSerializer.Deserialize <WeatherForecastWithObjectProperties>(jsonString);

            weatherForecastWithObjectProperties.DisplayPropertyValues();

            // <SnippetRegister>
            var deserializeOptions = new JsonSerializerOptions();

            deserializeOptions.Converters.Add(new ObjectToInferredTypesConverter());
            // </SnippetRegister>
            weatherForecastWithObjectProperties = JsonSerializer.Deserialize <WeatherForecastWithObjectProperties>(jsonString, deserializeOptions);
            weatherForecastWithObjectProperties.DisplayPropertyValues();
        }
コード例 #13
0
        public static void Run()
        {
            string jsonString;
            WeatherForecastWithPropertyNameAttribute weatherForecast =
                WeatherForecastFactories.CreateWeatherForecastWithPropertyNameAttribute();

            weatherForecast.DisplayPropertyValues();

            // <Serialize>
            var serializeOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented        = true
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);
            // </Serialize>
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            // <Deserialize>
            var deserializeOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            weatherForecast =
                JsonSerializer.Deserialize <WeatherForecastWithPropertyNameAttribute>(
                    jsonString, deserializeOptions);
            // </Deserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #14
0
        public static void Run()
        {
            string          jsonString;
            WeatherForecast weatherForecast =
                WeatherForecastFactories.CreateWeatherForecastCyrillic();

            weatherForecast.DisplayPropertyValues();

            Console.WriteLine("Default serialization - non-ASCII escaped");
            var options = new JsonSerializerOptions
            {
                WriteIndented = true
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            Console.WriteLine(jsonString);
            Console.WriteLine();

            Console.WriteLine("Serialize language sets unescaped");
            // <LanguageSets>
            options = new JsonSerializerOptions
            {
                Encoder       = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.Cyrillic),
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </LanguageSets>
            Console.WriteLine(jsonString);
            Console.WriteLine();

            Console.WriteLine("Serialize selected unescaped characters");
            // <SelectedCharacters>
            var encoderSettings = new TextEncoderSettings();

            encoderSettings.AllowCharacters('\u0436', '\u0430');
            encoderSettings.AllowRange(UnicodeRanges.BasicLatin);
            options = new JsonSerializerOptions
            {
                Encoder       = JavaScriptEncoder.Create(encoderSettings),
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </SelectedCharacters>
            Console.WriteLine(jsonString);
            Console.WriteLine();

            Console.WriteLine("Serialize using unsafe relaxed encoder");
            // <UnsafeRelaxed>
            options = new JsonSerializerOptions
            {
                Encoder       = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </UnsafeRelaxed>
            Console.WriteLine(jsonString);
        }
コード例 #15
0
        public static void Run()
        {
            // Serialize to create input JSON
            WeatherForecastWithLong weatherForecast = WeatherForecastFactories.CreateWeatherForecastWithLong();
            var serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            string jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);

            Console.WriteLine($"JSON output:\n{jsonString}\n");

            weatherForecast = JsonSerializer.Deserialize <WeatherForecastWithLong>(jsonString);
            weatherForecast.DisplayPropertyValues();
        }
コード例 #16
0
        public static void Run()
        {
            WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            byte[] jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(
                weatherForecast,
                new JsonSerializerOptions {
                WriteIndented = true
            });

            // <SnippetDeserialize>
            var options = new JsonReaderOptions
            {
                AllowTrailingCommas = true,
                CommentHandling     = JsonCommentHandling.Skip
            };
            Utf8JsonReader reader = new Utf8JsonReader(jsonUtf8Bytes, options);

            while (reader.Read())
            {
                Console.Write(reader.TokenType);

                switch (reader.TokenType)
                {
                case JsonTokenType.PropertyName:
                case JsonTokenType.String:
                {
                    string text = reader.GetString();
                    Console.Write(" ");
                    Console.Write(text);
                    break;
                }

                case JsonTokenType.Number:
                {
                    int intValue = reader.GetInt32();
                    Console.Write(" ");
                    Console.Write(intValue);
                    break;
                }

                    // Other token types elided for brevity
                }
                Console.WriteLine();
            }
            // </SnippetDeserialize>
        }
コード例 #17
0
        public static void Run()
        {
            string jsonString;
            var    weatherForecast = WeatherForecastFactories.CreateWeatherForecastWithIgnoreAttribute();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            var options = new JsonSerializerOptions
            {
                WriteIndented = true
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </SnippetSerialize>
            Console.WriteLine(jsonString);
            Console.WriteLine();
        }
コード例 #18
0
ファイル: RoundtripToFile.cs プロジェクト: yashbajra/samples
        public static void Run()
        {
            string          jsonString;
            string          fileName        = "WeatherForecast.json";
            WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            jsonString = JsonSerializer.Serialize(weatherForecast);
            File.WriteAllText(fileName, jsonString);
            // </SnippetSerialize>
            Console.WriteLine($"The result is in {fileName}\n");

            // <SnippetDeserialize>
            jsonString      = File.ReadAllText(fileName);
            weatherForecast = JsonSerializer.Deserialize <WeatherForecast>(jsonString);
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #19
0
        public static void Run()
        {
            string jsonString;
            WeatherForecastWithROProperty weatherForecast =
                WeatherForecastFactories.CreateWeatherForecastWithROProperty();

            weatherForecast.DisplayPropertyValues();

            // <Serialize>
            var options = new JsonSerializerOptions
            {
                IgnoreReadOnlyProperties = true,
                WriteIndented            = true
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </Serialize>
            Console.WriteLine(jsonString);
            Console.WriteLine();
        }
コード例 #20
0
        public static void Run()
        {
            string jsonString;
            var    weatherForecast = WeatherForecastFactories.CreateWeatherForecastWithConverterAttribute();

            weatherForecast.DisplayPropertyValues();

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

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

            // <SnippetDeserialize>
            weatherForecast = JsonSerializer.Deserialize <WeatherForecastWithConverterAttribute>(jsonString);
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #21
0
        public static void Run()
        {
            string          jsonString;
            WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.Summary = null;
            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            var options = new JsonSerializerOptions
            {
                IgnoreNullValues = true,
                WriteIndented    = true
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </SnippetSerialize>
            Console.WriteLine(jsonString);
            Console.WriteLine();
        }
コード例 #22
0
        public static void Run()
        {
            string          jsonString;
            var             weatherForecastDerived = WeatherForecastFactories.CreateWeatherForecastDerived();
            WeatherForecast weatherForecast        = weatherForecastDerived;

            weatherForecast.DisplayPropertyValues();

            Console.WriteLine("Base class generic type - derived class properties omitted");
            // <SnippetSerializeDefault>
            var serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true
            };

            jsonString = JsonSerializer.Serialize <WeatherForecast>(weatherForecast, serializeOptions);
            // </SnippetSerializeDefault>

            Console.WriteLine($"JSON output:\n{jsonString}\n");

            Console.WriteLine("Object generic type parameter - derived class properties included");
            // <SnippetSerializeObject>
            serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize <object>(weatherForecast, serializeOptions);
            // </SnippetSerializeObject>
            Console.WriteLine($"JSON output:\n{jsonString}\n");


            Console.WriteLine("GetType() type parameter - derived class properties included");
            // <SnippetSerializeGetType>
            serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize(weatherForecast, weatherForecast.GetType(), serializeOptions);
            // </SnippetSerializeGetType>
            Console.WriteLine($"JSON output:\n{jsonString}\n");
        }
コード例 #23
0
ファイル: RoundtripToFileAsync.cs プロジェクト: mavasani/docs
        public static async Task RunAsync()
        {
            string          fileName        = "WeatherForecastAsync.json";
            WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.DisplayPropertyValues();

            // <Serialize>
            using FileStream createStream = File.Create(fileName);
            await JsonSerializer.SerializeAsync(createStream, weatherForecast);

            // </Serialize>
            Console.WriteLine($"The result is in {fileName}\n");

            // <Deserialize>
            using FileStream openStream = File.OpenRead(fileName);
            weatherForecast             = await JsonSerializer.DeserializeAsync <WeatherForecast>(openStream);

            // </Deserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #24
0
        public static async Task RunAsync()
        {
            string fileName        = "WeatherForecastAsync.json";
            string fileNameUtf8    = "WeatherForecastAsyncUtf8";
            var    weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            using (FileStream fs = File.Create(fileName))
            {
                await JsonSerializer.SerializeAsync(fs, weatherForecast);
            }
            // </SnippetSerialize>
            Console.WriteLine($"The result is in {fileName}\n");

            // <SnippetDeserialize>
            using (FileStream fs = File.OpenRead(fileName))
            {
                weatherForecast = await JsonSerializer.DeserializeAsync <WeatherForecast>(fs);
            }
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();

            using (FileStream fs = File.Create(fileNameUtf8))
            {
                using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
                {
                    await JsonSerializer.SerializeAsync(fs, weatherForecast);
                }
            }
            Console.WriteLine($"The result is in {fileNameUtf8}\n");
            using (FileStream fs = File.OpenRead(fileNameUtf8))
            {
                //System.Text.Json.JsonException: '0xEF' is invalid after a single JSON value. Expected end of data.
                //weatherForecast = await JsonSerializer.DeserializeAsync<WeatherForecast>(fs);
            }
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #25
0
        public static void Run()
        {
            string jsonString;
            WeatherForecastWithTemperatureStruct weatherForecast = WeatherForecastFactories.CreateWeatherForecastWithTemperatureStruct();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            var serializeOptions = new JsonSerializerOptions
            {
                WriteIndented = true
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);
            // </SnippetSerialize>
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            // <SnippetDeserialize>
            weatherForecast = JsonSerializer.Deserialize <WeatherForecastWithTemperatureStruct>(jsonString);
            weatherForecast.DisplayPropertyValues();
            // </SnippetDeserialize>
        }
コード例 #26
0
        public static void Run()
        {
            string jsonString;
            WeatherForecastWithDictionary weatherForecast = WeatherForecastFactories.CreateWeatherForecastWithDictionary();

            weatherForecast.DisplayPropertyValues();

            // <Serialize>
            var options = new JsonSerializerOptions
            {
                DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented       = true
            };

            jsonString = JsonSerializer.Serialize(weatherForecast, options);
            // </Serialize>
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            // <Deserialize>
            weatherForecast = JsonSerializer.Deserialize <WeatherForecastWithDictionary>(jsonString) !;
            // </Deserialize>
            weatherForecast !.DisplayPropertyValues();
        }
コード例 #27
0
        public static async Task RunAsync()
        {
            string          fileName        = "WeatherForecastAsync.json";
            WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            using (FileStream fs = File.Create(fileName))
            {
                await JsonSerializer.SerializeAsync(fs, weatherForecast);
            }
            // </SnippetSerialize>
            Console.WriteLine($"The result is in {fileName}\n");

            // <SnippetDeserialize>
            using (FileStream fs = File.OpenRead(fileName))
            {
                weatherForecast = await JsonSerializer.DeserializeAsync <WeatherForecast>(fs);
            }
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();
        }
コード例 #28
0
        public static void Run()
        {
            string          jsonString;
            var             weatherForecastDerived = WeatherForecastFactories.CreateWeatherForecastDerived();
            WeatherForecast weatherForecast        = weatherForecastDerived;

            weatherForecast.DisplayPropertyValues();

            Console.WriteLine("Base class generic type - derived class properties omitted");
            // <SerializeDefault>
            var options = new JsonSerializerOptions
            {
                WriteIndented = true
            };

            jsonString = JsonSerializer.Serialize <WeatherForecast>(weatherForecast, options);
            // </SerializeDefault>

            Console.WriteLine($"JSON output:\n{jsonString}\n");

            Console.WriteLine("Object generic type parameter - derived class properties included");
            // <SerializeObject>
            options = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize <object>(weatherForecast, options);
            // </SerializeObject>
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            Console.WriteLine("GetType() type parameter - derived class properties included");
            // <SerializeGetType>
            options = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize(weatherForecast, weatherForecast.GetType(), options);
            // </SerializeGetType>
            Console.WriteLine($"JSON output:\n{jsonString}\n");

            Console.WriteLine("Extra properties on interface implementations included only for object properties");
            // <SerializeInterface>
            var forecasts = new Forecasts
            {
                Monday = new Forecast
                {
                    Date = DateTime.Parse("2020-01-06"),
                    TemperatureCelsius = 10,
                    Summary            = "Cool",
                    WindSpeed          = 8
                },
                Tuesday = new Forecast
                {
                    Date = DateTime.Parse("2020-01-07"),
                    TemperatureCelsius = 11,
                    Summary            = "Rainy",
                    WindSpeed          = 10
                }
            };

            options = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize(forecasts, options);
            // </SerializeInterface>
            Console.WriteLine($"{jsonString}\n");

            WeatherForecastWithPrevious weatherForecastWithPrevious =
                WeatherForecastFactories.CreateWeatherForecastWithPrevious();
            WeatherForecastWithPreviousAsObject weatherForecastWithPreviousAsObject =
                WeatherForecastFactories.CreateWeatherForecastWithPreviousAsObject();

            Console.WriteLine("Second level derived class properties included only for object properties");
            // <SerializeSecondLevel>
            options = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            jsonString = JsonSerializer.Serialize(weatherForecastWithPreviousAsObject, options);
            // </SerializeSecondLevel>
            Console.WriteLine($"JSON output with WindSpeed:\n{jsonString}\n");
            jsonString = JsonSerializer.Serialize(
                weatherForecastWithPrevious,
                options);
            Console.WriteLine($"JSON output without WindSpeed:\n{jsonString}\n");
        }