From f747d15fbdcd9dbf75045d36a956bce22a120af5 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Sat, 19 Oct 2024 08:18:17 -0700 Subject: [PATCH] More STJ updates for .NET 9 (#43118) * manipulate property order * add note about AllowOutOfOrderMetadataProperties --- docs/core/whats-new/dotnet-9/libraries.md | 2 + .../weakly-typed-json-serialization-sample.md | 2 +- .../system-text-json/custom-contracts.md | 6 +-- .../system-text-json/polymorphism.md | 23 +++++++---- .../system-text-json/preserve-references.md | 4 +- .../csharp/JsonNodePropertyOrder.cs | 39 +++++++++++++++++++ .../serialization/system-text-json/use-dom.md | 8 ++++ 7 files changed, 71 insertions(+), 13 deletions(-) create mode 100644 docs/standard/serialization/system-text-json/snippets/use-dom-utf8jsonreader-utf8jsonwriter/csharp/JsonNodePropertyOrder.cs diff --git a/docs/core/whats-new/dotnet-9/libraries.md b/docs/core/whats-new/dotnet-9/libraries.md index aeb42b7cee2dd..3ea8640e2e394 100644 --- a/docs/core/whats-new/dotnet-9/libraries.md +++ b/docs/core/whats-new/dotnet-9/libraries.md @@ -544,6 +544,8 @@ The type now exposes ordered dictionary–like :::code language="csharp" source="../snippets/dotnet-9/csharp/Serialization.cs" id="PropertyOrder"::: +For more information, see [Manipulate property order](../../../standard/serialization/system-text-json/use-dom.md#manipulate-property-order). + ### Customize enum member names The new attribute can be used to customize the names of individual enum members for types that are serialized as strings: diff --git a/docs/framework/wcf/samples/weakly-typed-json-serialization-sample.md b/docs/framework/wcf/samples/weakly-typed-json-serialization-sample.md index ff4ebbc2e27fe..0056c916679f0 100644 --- a/docs/framework/wcf/samples/weakly-typed-json-serialization-sample.md +++ b/docs/framework/wcf/samples/weakly-typed-json-serialization-sample.md @@ -53,7 +53,7 @@ public class PersonalInfo This can be cumbersome, especially if the client has to handle more than one type of JSON object. -The `JsonObject` type provided by this sample introduces a weakly-typed representation of the deserialized JSON object. `JsonObject` relies on the natural mapping between JSON objects and .NET Framework dictionaries, and the mapping between JSON arrays and .NET Framework arrays. The following code shows the `JsonObject` type. +The `JsonObject` type provided by this sample introduces a weakly typed representation of the deserialized JSON object. `JsonObject` relies on the natural mapping between JSON objects and .NET Framework dictionaries, and the mapping between JSON arrays and .NET Framework arrays. The following code shows the `JsonObject` type. ```csharp // Instantiation of JsonObject json omitted diff --git a/docs/standard/serialization/system-text-json/custom-contracts.md b/docs/standard/serialization/system-text-json/custom-contracts.md index c72e8be6d8547..764c2d6da2042 100644 --- a/docs/standard/serialization/system-text-json/custom-contracts.md +++ b/docs/standard/serialization/system-text-json/custom-contracts.md @@ -50,7 +50,7 @@ There are two ways to plug into customization. Both involve obtaining a resolver The property indicates how the converter serializes a given type—for example, as an object or as an array, and whether its properties are serialized. You can query this property to determine which aspects of a type's JSON contract you can configure. There are four different kinds: | `JsonTypeInfo.Kind` | Description | -| - | - | +|---------------------|-------------| | | The converter will serialize the type into a JSON object and uses its properties. **This kind is used for most class and struct types and allows for the most flexibility.** | | | The converter will serialize the type into a JSON array. This kind is used for types like `List` and array. | | | The converter will serialize the type into a JSON object. This kind is used for types like `Dictionary`. | @@ -63,7 +63,7 @@ A modifier is an `Action` or a method with a delegate (for serialization) or delegate (for deserialization) for the property. | [Increment a property's value](#example-increment-a-propertys-value) | | Add or remove properties | `JsonTypeInfoKind.Object` | Add or remove items from the list. | [Serialize private fields](#example-serialize-private-fields) | | Conditionally serialize a property | `JsonTypeInfoKind.Object` | Modify the predicate for the property. | [Ignore properties with a specific type](#example-ignore-properties-with-a-specific-type) | @@ -114,7 +114,7 @@ Besides customizing a contract, there are other ways to influence serialization - By modifying , for example, to set a naming policy or serialize enumeration values as strings instead of numbers. - By writing a custom converter that does the actual work of writing the JSON and, during deserialization, constructing an object. -Contract customization is an improvement over these pre-existing customizations because you might not have access to the type to add attributes, and writing a custom converter is complex and hurts performance. +Contract customization is an improvement over these pre-existing customizations because you might not have access to the type to add attributes. In addition, writing a custom converter is complex and hurts performance. ## See also diff --git a/docs/standard/serialization/system-text-json/polymorphism.md b/docs/standard/serialization/system-text-json/polymorphism.md index 8c778cebfe98d..0998367e856d2 100644 --- a/docs/standard/serialization/system-text-json/polymorphism.md +++ b/docs/standard/serialization/system-text-json/polymorphism.md @@ -1,7 +1,7 @@ --- title: How to serialize properties of derived classes with System.Text.Json description: "Learn how to serialize polymorphic objects while serializing to and deserializing from JSON in .NET." -ms.date: 09/30/2022 +ms.date: 10/18/2024 no-loc: [System.Text.Json, Newtonsoft.Json] zone_pivot_groups: dotnet-version dev_langs: @@ -17,7 +17,7 @@ ms.topic: how-to # How to serialize properties of derived classes with System.Text.Json -In this article, you will learn how to serialize properties of derived classes with the `System.Text.Json` namespace. +In this article, you learn how to serialize properties of derived classes with the `System.Text.Json` namespace. ## Serialize properties of derived classes @@ -148,7 +148,7 @@ The following example shows the JSON that results from the preceding code: Beginning with .NET 7, `System.Text.Json` supports polymorphic type hierarchy serialization and deserialization with attribute annotations. | Attribute | Description | -|--|--| +|-----------|-------------| | | When placed on a type declaration, indicates that the specified subtype should be opted into polymorphic serialization. It also exposes the ability to specify a type discriminator. | | | When placed on a type declaration, indicates that the type should be serialized polymorphically. It also exposes various options to configure polymorphic serialization and deserialization for that type. | @@ -240,7 +240,7 @@ Public Class WeatherForecastWithCity End Class ``` -With the added metadata, specifically, the type discriminator, the serializer can serialize and deserialize the payload as the `WeatherForecastWithCity` type from its base type `WeatherForecastBase`. Serialization will emit JSON along with the type discriminator metadata: +With the added metadata, specifically, the type discriminator, the serializer can serialize and deserialize the payload as the `WeatherForecastWithCity` type from its base type `WeatherForecastBase`. Serialization emits JSON along with the type discriminator metadata: ```csharp WeatherForecastBase weather = new WeatherForecastWithCity @@ -289,14 +289,23 @@ WeatherForecastBase value = JsonSerializer.Deserialize(json Console.WriteLine(value is WeatherForecastWithCity); // True ``` -> [!NOTE] -> The type discriminator must be placed at the start of the JSON object, grouped together with other metadata properties like `$id` and `$ref`. - ```vb Dim value As WeatherForecastBase = JsonSerializer.Deserialize(json) Console.WriteLine(value is WeatherForecastWithCity) // True ``` + +> [!NOTE] +> By default, the `$type` discriminator must be placed at the start of the JSON object, grouped together with other metadata properties like `$id` and `$ref`. If you're reading data off an external API that places the `$type` discriminator in the middle of the JSON object, set to `true`: +> +> ```csharp +> JsonSerializerOptions options = new() { AllowOutOfOrderMetadataProperties = true }; +> JsonSerializer.Deserialize("""{"Name":"Name","$type":"derived"}""", options); +> ``` +> +> Be careful when you enable this flag, as it might result in over-buffering (and out-of-memory failures) when performing streaming deserialization of very large JSON objects. + + ### Mix and match type discriminator formats Type discriminator identifiers are valid in either `string` or `int` forms, so the following is valid: diff --git a/docs/standard/serialization/system-text-json/preserve-references.md b/docs/standard/serialization/system-text-json/preserve-references.md index 08ef17474f4a1..60a7e8f4a0f0c 100644 --- a/docs/standard/serialization/system-text-json/preserve-references.md +++ b/docs/standard/serialization/system-text-json/preserve-references.md @@ -37,7 +37,7 @@ The following code illustrates use of the `Preserve` setting. This feature can't be used to preserve value types or immutable types. On deserialization, the instance of an immutable type is created after the entire payload is read. So it would be impossible to deserialize the same instance if a reference to it appears within the JSON payload. -For value types, immutable types, and arrays, no reference metadata is serialized. On deserialization, an exception is thrown if `$ref` or `$id` is found. However, value types ignore `$id` (and `$values` in the case of collections) to make it possible to deserialize payloads that were serialized by using Newtonsoft.Json. Newtonsoft.Json does serialize metadata for such types. +For value types, immutable types, and arrays, no reference metadata is serialized. On deserialization, an exception is thrown if `$ref` or `$id` is found. However, value types ignore `$id` (and `$values` in the case of collections) to make it possible to deserialize payloads that were serialized by using Newtonsoft.Json, which does serialize metadata for such types. To determine if objects are equal, System.Text.Json uses , which uses reference equality () instead of value equality () when comparing two object instances. @@ -47,7 +47,7 @@ The class defines the be ### Persist reference metadata across multiple serialization and deserialization calls -By default, reference data is only cached for each call to or . To persist references from one `Serialize`/`Deserialize` call to another one, root the instance in the call site of `Serialize`/`Deserialize`. The following code shows an example for this scenario: +By default, reference data is only cached for each call to or . To persist references from one `Serialize` or `Deserialize` call to another one, root the instance in the call site of `Serialize`/`Deserialize`. The following code shows an example for this scenario: * You have a list of `Employee` objects and you have to serialize each one individually. * You want to take advantage of the references saved in the resolver for the `ReferenceHandler`. diff --git a/docs/standard/serialization/system-text-json/snippets/use-dom-utf8jsonreader-utf8jsonwriter/csharp/JsonNodePropertyOrder.cs b/docs/standard/serialization/system-text-json/snippets/use-dom-utf8jsonreader-utf8jsonwriter/csharp/JsonNodePropertyOrder.cs new file mode 100644 index 0000000000000..378c2cbcec9c7 --- /dev/null +++ b/docs/standard/serialization/system-text-json/snippets/use-dom-utf8jsonreader-utf8jsonwriter/csharp/JsonNodePropertyOrder.cs @@ -0,0 +1,39 @@ +using System.Linq; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Schema; + +namespace JsonNodePropertyOrder; + +public class Program +{ + public static void Main() + { + // + var schema = (JsonObject)JsonSerializerOptions.Default.GetJsonSchemaAsNode(typeof(MyPoco)); + + JsonNode? idValue; + switch (schema.IndexOf("$id")) + { + // $id property missing. + case < 0: + idValue = (JsonNode)"https://example.com/schema"; + schema.Insert(0, "$id", idValue); + break; + + // $id property already at the start of the object. + case 0: + break; + + // $id exists but not at the start of the object. + case int index: + idValue = schema[index]; + schema.RemoveAt(index); + schema.Insert(0, "$id", idValue); + break; + } + // + } +} + +class MyPoco { } diff --git a/docs/standard/serialization/system-text-json/use-dom.md b/docs/standard/serialization/system-text-json/use-dom.md index d42cfc28912aa..ead0601b396fa 100644 --- a/docs/standard/serialization/system-text-json/use-dom.md +++ b/docs/standard/serialization/system-text-json/use-dom.md @@ -85,6 +85,14 @@ The following example illustrates the result of using methods that take a `JsonS If you need features of `JsonSerializerOptions` other than custom converters, use `JsonSerializer` with strongly typed targets (such as the `Person` class in this example) rather than `JsonNode`. +### Manipulate property order + + is one of the elements in the payload of a , and it represents a mutable JSON object. Even though the type is modelled as an `IDictionary`, where each entry is a property of the object, it encapsulate an implicit property order. However, APIs such as and effectively model the type as an ordered dictionary by letting you insert and remove items at a specific index. These APIs allow modifications to object instances that can directly influence property order. + +The following code shows an example of adding or moving a specific property to the start of the object. + +:::code language="csharp" source="snippets/use-dom-utf8jsonreader-utf8jsonwriter/csharp/JsonNodePropertyOrder.cs" id="1"::: + ### Compare JsonNodes To compare two `JsonNode` objects for equality, including their descendant elements, use the method.