Skip to content

Commit 6d63bec

Browse files
authored
More System.Text.Json updates for .NET 9 (#43100)
1 parent b013edb commit 6d63bec

24 files changed

+293
-263
lines changed

.openpublishing.redirection.standard.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,11 @@
739739
"source_path_from_root": "/docs/standard/serialization/system-text-json-use-dom-utf8jsonreader-utf8jsonwriter.md",
740740
"redirect_url": "/dotnet/standard/serialization/system-text-json/use-dom"
741741
},
742+
{
743+
"source_path_from_root": "/docs/standard/serialization/system-text-json/json-schema-exporter.md",
744+
"redirect_url": "/dotnet/standard/serialization/system-text-json/extract-schema",
745+
"redirect_document_id": true
746+
},
742747
{
743748
"source_path_from_root": "/docs/standard/serialization/system-text-json/use-dom-utf8jsonreader-utf8jsonwriter.md",
744749
"redirect_url": "/dotnet/standard/serialization/system-text-json/use-dom",

docs/core/whats-new/dotnet-9/libraries.md

Lines changed: 3 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -493,33 +493,7 @@ If you want to serialize with the [default options that ASP.NET Core uses](../..
493493

494494
JSON is frequently used to represent types in method signatures as part of remote procedure&ndash;calling schemes. It's used, for example, as part of OpenAPI specifications, or as part of tool calling with AI services like those from OpenAI. Developers can serialize and deserialize .NET types as JSON using <xref:System.Text.Json>. But they also need to be able to get a JSON schema that describes the shape of the .NET type (that is, describes the shape of what would be serialized and what can be deserialized). <xref:System.Text.Json> now provides the <xref:System.Text.Json.Schema.JsonSchemaExporter> type, which supports generating a JSON schema that represents a .NET type.
495495

496-
The following code generates a JSON schema from a type.
497-
498-
:::code language="csharp" source="../snippets/dotnet-9/csharp/Serialization.cs" id="Schema":::
499-
500-
The type is defined as follows:
501-
502-
:::code language="csharp" source="../snippets/dotnet-9/csharp/Serialization.cs" id="Book":::
503-
504-
The generated schema is:
505-
506-
```json
507-
{
508-
"type": ["object", "null"],
509-
"properties": {
510-
"Title": {
511-
"type": "string"
512-
},
513-
"Author": {
514-
"type": ["string", "null"]
515-
},
516-
"PublishYear": {
517-
"type": "integer"
518-
}
519-
},
520-
"required": ["Title"]
521-
}
522-
```
496+
For more information, see [JSON schema exporter](../../../standard/serialization/system-text-json/extract-schema.md).
523497

524498
### Respect nullable annotations
525499

@@ -588,50 +562,9 @@ enum MyEnum
588562

589563
### Stream multiple JSON documents
590564

591-
<xref:System.Text.Json.Utf8JsonReader?displayProperty=nameWithType> now supports reading multiple, whitespace-separated JSON documents from a single buffer or stream. By default, the reader throws an exception if it detects any non-whitespace characters that are trailing the first top-level document. You can change this behavior using the <xref:System.Text.Json.JsonReaderOptions.AllowMultipleValues> flag:
592-
593-
```csharp
594-
JsonReaderOptions options = new() { AllowMultipleValues = true };
595-
Utf8JsonReader reader = new("null {} 1 \r\n [1,2,3]"u8, options);
596-
597-
reader.Read();
598-
Console.WriteLine(reader.TokenType); // Null
599-
600-
reader.Read();
601-
Console.WriteLine(reader.TokenType); // StartObject
602-
reader.Skip();
603-
604-
reader.Read();
605-
Console.WriteLine(reader.TokenType); // Number
565+
<xref:System.Text.Json.Utf8JsonReader?displayProperty=nameWithType> now supports reading multiple, whitespace-separated JSON documents from a single buffer or stream. By default, the reader throws an exception if it detects any non-whitespace characters that are trailing the first top-level document. You can change this behavior using the <xref:System.Text.Json.JsonReaderOptions.AllowMultipleValues> flag.
606566

607-
reader.Read();
608-
Console.WriteLine(reader.TokenType); // StartArray
609-
reader.Skip();
610-
611-
Console.WriteLine(reader.Read()); // False
612-
```
613-
614-
This flag also makes it possible to read JSON from payloads that might contain trailing data that's invalid JSON:
615-
616-
```csharp
617-
Utf8JsonReader reader = new("[1,2,3] <NotJson/>"u8, new() { AllowMultipleValues = true });
618-
619-
reader.Read();
620-
reader.Skip(); // Success
621-
reader.Read(); // throws JsonReaderException
622-
```
623-
624-
When it comes to streaming deserialization, a new <xref:System.Text.Json.JsonSerializer.DeserializeAsyncEnumerable%60%601(System.IO.Stream,System.Boolean,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)?displayProperty=nameWithType> overload makes streaming multiple top-level values possible. By default, the method attempts to stream elements that are contained in a top-level JSON array. You can toggle this behavior using the new `topLevelValues` flag:
625-
626-
```csharp
627-
ReadOnlySpan<byte> utf8Json = """[0] [0,1] [0,1,1] [0,1,1,2] [0,1,1,2,3]"""u8;
628-
using var stream = new MemoryStream(utf8Json.ToArray());
629-
630-
await foreach (int[] item in JsonSerializer.DeserializeAsyncEnumerable<int[]>(stream, topLevelValues: true))
631-
{
632-
Console.WriteLine(item.Length);
633-
}
634-
```
567+
For more information, see [Read multiple JSON documents](../../../standard/serialization/system-text-json/use-utf8jsonreader.md#read-multiple-json-documents).
635568

636569
## Spans
637570

docs/fundamentals/toc.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,7 @@ items:
786786
- name: Customize contracts
787787
href: ../standard/serialization/system-text-json/custom-contracts.md
788788
- name: Extract JSON schema
789-
href: ../standard/serialization/system-text-json/json-schema-exporter.md
789+
href: ../standard/serialization/system-text-json/extract-schema.md
790790
- name: XML and SOAP serialization
791791
items:
792792
- name: Overview

docs/standard/serialization/system-text-json/json-schema-exporter.md renamed to docs/standard/serialization/system-text-json/extract-schema.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ dev_langs:
88

99
# JSON schema exporter
1010

11-
The new <xref:System.Text.Json.Schema.JsonSchemaExporter> class lets you extract [JSON schema](https://json-schema.org/) documents from .NET types using either a <xref:System.Text.Json.JsonSerializerOptions> or <xref:System.Text.Json.Serialization.Metadata.JsonTypeInfo> instance. The resultant schema provides a specification of the JSON serialization contract for the type.
11+
The <xref:System.Text.Json.Schema.JsonSchemaExporter> class, introduced in .NET 9, lets you extract [JSON schema](https://json-schema.org/) documents from .NET types using either a <xref:System.Text.Json.JsonSerializerOptions> or <xref:System.Text.Json.Serialization.Metadata.JsonTypeInfo> instance. The resultant schema provides a specification of the JSON serialization contract for the .NET type. The schema describes the shape of what would be serialized and what can be deserialized.
1212

1313
The following code snippet shows an example.
1414

docs/standard/serialization/system-text-json/handle-overflow.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ helpviewer_keywords:
1414
ms.topic: how-to
1515
---
1616

17-
# How to handle overflow JSON or use JsonElement or JsonNode in System.Text.Json
17+
# How to handle overflow JSON or use JsonElement or JsonNode
1818

1919
This article shows how to handle overflow JSON with the <xref:System.Text.Json> namespace. It also shows how to deserialize into <xref:System.Text.Json.JsonElement> or <xref:System.Text.Json.Nodes.JsonNode>, as an alternative for other scenarios where the target type might not perfectly match all of the JSON being deserialized.
2020

@@ -86,7 +86,7 @@ The following example shows a round trip from JSON to a deserialized object and
8686

8787
## Deserialize into JsonElement or JsonNode
8888

89-
If you just want to be flexible about what JSON is acceptable for a particular property, an alternative is to deserialize into <xref:System.Text.Json.JsonElement> or <xref:System.Text.Json.Nodes.JsonNode>. Any valid JSON property can be deserialized into `JsonElement` or `JsonNode`. Choose `JsonElement` to create an immutable object or `JsonNode` to create a mutable object.
89+
If you just want to be flexible about what JSON is acceptable for a particular property, an alternative is to deserialize into <xref:System.Text.Json.JsonElement> or <xref:System.Text.Json.Nodes.JsonNode>. Any valid JSON property can be deserialized into `JsonElement` or `JsonNode`. Choose `JsonElement` to create an *immutable* object or `JsonNode` to create a *mutable* object.
9090

9191
The following example shows a round trip from JSON and back to JSON for a class that includes properties of type `JsonElement` and `JsonNode`.
9292

docs/standard/serialization/system-text-json/how-to.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ The following example creates JSON as a string:
3333
:::code language="csharp" source="snippets/how-to/csharp/SerializeBasic.cs" id="all" highlight="23":::
3434
:::code language="vb" source="snippets/how-to/vb/RoundtripToString.vb" id="Serialize":::
3535

36-
The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.
36+
The JSON output is *minified* (whitespace, indentation, and new-line characters are removed) by default.
3737

3838
The following example uses synchronous code to create a JSON file:
3939

@@ -104,6 +104,8 @@ To pretty-print the JSON output, set <xref:System.Text.Json.JsonSerializerOption
104104
:::code language="csharp" source="snippets/how-to/csharp/SerializeWriteIndented.cs" highlight="24":::
105105
:::code language="vb" source="snippets/how-to/vb/RoundtripToString.vb" id="SerializePrettyPrint":::
106106

107+
Starting in .NET 9, you can also customize the indent character and size using <xref:System.Text.Json.JsonSerializerOptions.IndentCharacter> and <xref:System.Text.Json.JsonSerializerOptions.IndentSize>.
108+
107109
> [!TIP]
108110
> If you use `JsonSerializerOptions` repeatedly with the same options, don't create a new `JsonSerializerOptions` instance each time you use it. Reuse the same instance for every call. For more information, see [Reuse JsonSerializerOptions instances](configure-options.md#reuse-jsonserializeroptions-instances).
109111

docs/standard/serialization/system-text-json/migrate-from-newtonsoft.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -782,8 +782,8 @@ If you need to continue to use `Newtonsoft.Json` for certain target frameworks,
782782

783783
Starting in .NET 9, you can customize the indentation character and size for <xref:System.Text.Json.Utf8JsonWriter> using options exposed by the <xref:System.Text.Json.JsonWriterOptions> struct:
784784

785-
* `JsonWriterOptions.IndentCharacter` <!-- <xref:System.Text.Json.JsonWriterOptions.IndentCharacter> -->
786-
* `JsonWriterOptions.IndentSize` <!-- <xref:System.Text.Json.JsonWriterOptions.IndentSize> -->
785+
* <xref:System.Text.Json.JsonWriterOptions.IndentCharacter?displayProperty=nameWithType>
786+
* <xref:System.Text.Json.JsonWriterOptions.IndentSize?displayProperty=nameWithType>
787787

788788
::: zone-end
789789

docs/standard/serialization/system-text-json/snippets/how-to-contd/csharp/ImmutableTypes.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public struct Forecast
88
public DateTime Date { get; }
99
public int TemperatureC { get; }
1010
public string Summary { get; }
11-
11+
1212
[JsonConstructor]
1313
public Forecast(DateTime date, int temperatureC, string summary) =>
1414
(Date, TemperatureC, Summary) = (date, temperatureC, summary);
@@ -27,7 +27,7 @@ public static void Main()
2727
""";
2828
Console.WriteLine($"Input JSON: {json}");
2929

30-
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
30+
var options = JsonSerializerOptions.Web;
3131

3232
Forecast forecast = JsonSerializer.Deserialize<Forecast>(json, options);
3333

docs/standard/serialization/system-text-json/snippets/how-to-contd/csharp/ImmutableTypesCtorParms.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public readonly struct Forecast
99
[JsonPropertyName("celsius")]
1010
public int TemperatureC { get; }
1111
public string Summary { get; }
12-
12+
1313
[JsonConstructor]
1414
public Forecast(DateTime date, int temperatureC, string summary) =>
1515
(Date, TemperatureC, Summary) = (date, temperatureC, summary);
@@ -28,7 +28,7 @@ public static void Main()
2828
""";
2929
Console.WriteLine($"Input JSON: {json}");
3030

31-
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
31+
var options = JsonSerializerOptions.Web;
3232

3333
Forecast forecast = JsonSerializer.Deserialize<Forecast>(json, options);
3434

docs/standard/serialization/system-text-json/snippets/how-to-contd/csharp/SystemTextJsonHowTo.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net8.0</TargetFramework>
5+
<TargetFramework>net9.0</TargetFramework>
66
<StartupObject>SystemTextJsonHowTo.Program</StartupObject>
77
<Nullable>enable</Nullable>
88
<ImplicitUsings>enable</ImplicitUsings>

0 commit comments

Comments
 (0)