diff --git a/docs/standard/serialization/system-text-json-ignore-properties.md b/docs/standard/serialization/system-text-json-ignore-properties.md index f785cac3433c6..57f43181ea7bf 100644 --- a/docs/standard/serialization/system-text-json-ignore-properties.md +++ b/docs/standard/serialization/system-text-json-ignore-properties.md @@ -1,7 +1,7 @@ --- title: How to ignore properties with System.Text.Json description: "Learn how to ignore properties when serializing with System.Text.Json in .NET." -ms.date: 11/30/2020 +ms.date: 01/26/2021 no-loc: [System.Text.Json, Newtonsoft.Json] zone_pivot_groups: dotnet-version helpviewer_keywords: @@ -30,6 +30,8 @@ When serializing C# objects to JavaScript Object Notation (JSON), by default, al * [All null-value properties](#ignore-all-null-value-properties) ::: zone-end +This article also includes a section about how to [ignore null when deserializing](#ignore-null-when-deserializing). + ## Ignore individual properties To ignore individual properties, use the [[JsonIgnore]](xref:System.Text.Json.Serialization.JsonIgnoreAttribute) attribute. @@ -127,6 +129,34 @@ The There is no built-in way to prevent serialization of properties with value type defaults in `System.Text.Json` in .NET Core 3.1. ::: zone-end +## Ignore null when deserializing + +By default, if a property in JSON is null, the corresponding property in the target object is set to null. In some scenarios, the target property might have a default value, and you don't want a null value to override the default. + +For example, suppose the following code represents your target object: + +[!code-csharp[](snippets/system-text-json-how-to/csharp/WeatherForecast.cs?name=WFWithDefault)] + +And suppose the following JSON is deserialized: + +```json +{ + "Date": "2019-08-01T00:00:00-07:00", + "TemperatureCelsius": 25, + "Summary": null +} +``` + +After deserialization, the `Summary` property of the `WeatherForecastWithDefault` object is null. + +To change this behavior, set to `true`, as shown in the following example: + +[!code-csharp[](snippets/system-text-json-how-to/csharp/DeserializeIgnoreNull.cs?name=Deserialize)] + +With this option, the `Summary` property of the `WeatherForecastWithDefault` object is the default value "No summary" after deserialization. + +Null values in the JSON are ignored only if they are valid. Null values for non-nullable value types cause exceptions. + ## See also * [System.Text.Json overview](system-text-json-overview.md)