Skip to content

Commit 11f3a33

Browse files
authored
Follow-up to #14208 (#14439)
1 parent f2c82f0 commit 11f3a33

File tree

2 files changed

+55
-42
lines changed

2 files changed

+55
-42
lines changed

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

Lines changed: 52 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
---
22
title: "How to serialize JSON - .NET"
3-
ms.date: "09/02/2019"
3+
author: tdykstra
4+
ms.author: tdykstra
5+
ms.date: "09/16/2019"
46
helpviewer_keywords:
57
- "JSON serialization"
68
- "serializing objects"
@@ -17,7 +19,7 @@ This article shows how to use the <xref:System.Text.Json> namespace to serialize
1719

1820
## Namespaces
1921

20-
The <xref:System.Text.Json> namespace contains all the entry points and the main types. The <xref:System.Text.Json.Serialization> namespace contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization. Therefore the code examples shown in this article require one or both of the following `using` directives:
22+
The <xref:System.Text.Json> namespace contains all the entry points and the main types. The <xref:System.Text.Json.Serialization> namespace contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization. Therefore, the code examples shown in this article require one or both of the following `using` directives:
2123

2224
```csharp
2325
using System.Text.Json;
@@ -28,14 +30,18 @@ Attributes from the <xref:System.Runtime.Serialization> namespace aren't current
2830

2931
## How to write .NET objects to JSON (serialize)
3032

31-
To write JSON to a string, call [JsonSerializer.Serialize](xref:System.Text.Json.JsonSerializer.Serialize*), using a generic type parameter or generic type inference:
33+
To write JSON to a string, call the <xref:System.Text.Json.JsonSerializer.Serialize%2A?displayProperty=nameWithType> method. The following example uses an overload with a generic type parameter:
3234

3335
```csharp
36+
WeatherForecast weatherForecast;
37+
//...
3438
string json = JsonSerializer.Serialize<WeatherForecast>(weatherForecast);
3539
```
3640

41+
You can omit the generic type parameter and use generic type inference instead:
42+
3743
```csharp
38-
WeatherForecast weatherForecast = ... ;
44+
WeatherForecast weatherForecast;
3945
//...
4046
string json = JsonSerializer.Serialize(weatherForecast);
4147
```
@@ -112,7 +118,7 @@ Overloads of <xref:System.Text.Json.JsonSerializer.Serialize%2A> let you seriali
112118

113119
### Serialize to UTF-8
114120

115-
Call [JsonSerializer.SerializeToUtf8Bytes](xref:System.Text.Json.JsonSerializer.SerializeToUtf8Bytes*):
121+
To serialize to UTF-8, call the <xref:System.Text.Json.JsonSerializer.SerializeToUtf8Bytes%2A?displayProperty=nameWithType> method:
116122

117123
```csharp
118124
byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes<WeatherForecast>(weatherForecast);
@@ -122,29 +128,29 @@ As an alternative, a <xref:System.Text.Json.JsonSerializer.Serialize%2A> overloa
122128

123129
Serializing to UTF-8 is about 5-10% faster than using the string-based methods. The difference is because the bytes (as UTF-8) don't need to be converted to strings (UTF-16).
124130

125-
## Default serialization behavior
131+
## Serialization behavior
126132

127-
* All public properties are serialized. You can [specify properties to exclude](#exclude-properties).
128-
* The [default encoder](xref:System.Text.Encodings.Web.JavaScriptEncoder.Default) escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to [the JSON spec](https://tools.ietf.org/html/rfc8259#section-7).
129-
* JSON is minified. You can optionally [pretty-print the JSON](#serialize-to-formatted-json).
130-
* Casing of JSON names matches the .NET names. You can [customize JSON name casing](#customize-json-names).
131-
* [Circular references](https://github.com/dotnet/corefx/issues/38579) are detected and exceptions thrown.
132-
* Fields are excluded.
133+
* By default, all public properties are serialized. You can [specify properties to exclude](#exclude-properties).
134+
* The [default encoder](xref:System.Text.Encodings.Web.JavaScriptEncoder.Default) escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to [the JSON spec](https://tools.ietf.org/html/rfc8259#section-7).
135+
* By default, JSON is minified. You can [pretty-print the JSON](#serialize-to-formatted-json).
136+
* By default, casing of JSON names matches the .NET names. You can [customize JSON name casing](#customize-json-names).
137+
* Circular references are detected and exceptions thrown. For more information, see the [issue on circular references](https://github.com/dotnet/corefx/issues/38579) in the dotnet/corefx repository on GitHub.
138+
* Currently, fields are excluded.
133139

134140
Supported types include:
135141

136-
* .NET primitives that map to JavaScript primitives, such as numeric types, strings, and boolean.
142+
* .NET primitives that map to JavaScript primitives, such as numeric types, strings, and Boolean.
137143
* User-defined [Plain Old CLR Objects (POCOs)](https://stackoverflow.com/questions/250001/poco-definition).
138144
* One-dimensional and jagged arrays (`ArrayName[][]`).
139145
* `Dictionary<string,TValue>` where `TValue` is `object`, `JsonElement`, or a POCO.
140-
* [Collection types](https://github.com/dotnet/corefx/issues/36643) from the following namespaces:
146+
* Collections from the following namespaces. For more information, see the [issue on collection support](https://github.com/dotnet/corefx/issues/36643) in the dotnet/corefx repository on GitHub.
141147
* <xref:System.Collections>
142148
* <xref:System.Collections.Generic>
143149
* <xref:System.Collections.Immutable>
144150

145151
## How to read JSON into .NET objects (deserialize)
146152

147-
To deserialize from a string, call [JsonSerializer.Deserialize](xref:System.Text.Json.JsonSerializer.Deserialize*):
153+
To deserialize from a string, call the <xref:System.Text.Json.JsonSerializer.Deserialize%2A?displayProperty=nameWithType> method, as shown in the following example:
148154

149155
```csharp
150156
string json = ... ;
@@ -158,36 +164,36 @@ Overloads of <xref:System.Text.Json.JsonSerializer.Deserialize*> let you deseria
158164

159165
### Deserialize from UTF-8
160166

161-
Call a [JsonSerializer.Deserialize](xref:System.Text.Json.JsonSerializer.Deserialize*) overload that takes a `Utf8JsonReader` or a `ReadOnlySpan<byte>`:
167+
To deserialize from UTF-8, call a <xref:System.Text.Json.JsonSerializer.Deserialize%2A?displayProperty=nameWithType> overload that takes a `Utf8JsonReader` or a `ReadOnlySpan<byte>`, as shown in the following examples:
162168

163169
```csharp
164-
byte[] utf8Json = ... ;
165-
170+
byte[] utf8Json;
171+
//...
166172
var readOnlySpan = new ReadOnlySpan<byte>(utf8Json);
167173
weatherForecast = JsonSerializer.Deserialize<WeatherForecastMin>(readOnlySpan);
168174
```
169175

170176
```csharp
171-
byte[] utf8Json = ... ;
172-
177+
byte[] utf8Json;
178+
//...
173179
var utf8Reader = new Utf8JsonReader(utf8Json);
174180
weatherForecast = JsonSerializer.Deserialize<WeatherForecastMin>(ref utf8Reader);
175181
```
176182

177-
## Default deserialization behavior
183+
## Deserialization behavior
178184

179-
* Property name matching is case-sensitive. You can optionally specify [case-insensitivity](#case-insensitive-property-matching).
185+
* By default, property name matching is case-sensitive. You can [specify case-insensitivity](#case-insensitive-property-matching).
180186
* If the JSON contains a value for a read-only property, the value is ignored and no exception is thrown.
181187
* Deserialization to reference types without a parameterless constructor isn't supported.
182-
* Deserialization to [immutable objects](https://github.com/dotnet/corefx/issues/38569) or [read-only properties](https://github.com/dotnet/corefx/issues/38163) isn't supported.
183-
* Enums are supported as numbers.
188+
* Deserialization to immutable objects or read-only properties isn't supported. For more information, see the GitHub [issue on immutable object support](https://github.com/dotnet/corefx/issues/38569) and the [issue on read-only property support](https://github.com/dotnet/corefx/issues/38163) in the dotnet/corefx repository on GitHub.
189+
* By default, enums are supported as numbers.
184190
* Fields aren't supported.
185-
* Comments or trailing commas in the JSON throw exceptions. You can [allow comments and trailing commas](#allow-comments-and-trailing-commas).
191+
* By default, comments or trailing commas in the JSON throw exceptions. You can [allow comments and trailing commas](#allow-comments-and-trailing-commas) if needed.
186192
* The [default maximum depth](xref:System.Text.Json.JsonReaderOptions.MaxDepth) is 64.
187193

188194
## Serialize to formatted JSON
189195

190-
Set <xref:System.Text.Json.JsonSerializerOptions.WriteIndented> to true:
196+
To pretty-print the JSON output, set <xref:System.Text.Json.JsonSerializerOptions.WriteIndented?displayProperty=nameWithType> to `true`:
191197

192198
```csharp
193199
var options = new JsonSerializerOptions
@@ -218,7 +224,7 @@ class WeatherForecast
218224

219225
## Allow comments and trailing commas
220226

221-
Set <xref:System.Text.Json.JsonSerializerOptions.ReadCommentHandling> to `JsonCommentHandling.Skip`, and set <xref:System.Text.Json.JsonSerializerOptions.AllowTrailingCommas> to true:
227+
By default comments and trailing commas are not allowed in JSON. To allow comments in the JSON, set the <xref:System.Text.Json.JsonSerializerOptions.ReadCommentHandling?displayProperty=nameWithType> property to `JsonCommentHandling.Skip`. And to allow trailing commas, set the <xref:System.Text.Json.JsonSerializerOptions.AllowTrailingCommas?displayProperty=nameWithType> property to `true`. The following example shows how to allow both:
222228

223229
```csharp
224230
var options = new JsonSerializerOptions
@@ -241,14 +247,14 @@ Here's example JSON with comments and a trailing comma:
241247

242248
## Customize JSON names
243249

244-
This section explains how to:
250+
By default, property names and dictionary keys are unchanged in the JSON output, including case. This section explains how to:
245251

246252
* Customize individual property names
247253
* Convert all property names to camel case
248254
* Implement a custom property naming policy
249255
* Convert dictionary keys to camel case
250256

251-
There's no support for automatically [converting enums to camel case](https://github.com/dotnet/corefx/issues/37725).
257+
Currently, there's no support for automatically converting enums to camel case. For more information, see the [issue on enum camel case support](https://github.com/dotnet/corefx/issues/37725) in the dotnet/corefx repository on GitHub.
252258

253259
### Customize individual property names
254260

@@ -283,7 +289,7 @@ The property name set by this attribute:
283289

284290
### Use camel case for all JSON property names
285291

286-
Set <xref:System.Text.Json.JsonSerializerOptions.PropertyNamingPolicy> to `JsonNamingPolicy.CamelCase`:
292+
To use camel case for all JSON property names, set <xref:System.Text.Json.JsonSerializerOptions.PropertyNamingPolicy?displayProperty=nameWithType> to `JsonNamingPolicy.CamelCase`, as shown in the following example:
287293

288294
```csharp
289295
var options = new JsonSerializerOptions
@@ -322,7 +328,7 @@ The camel case property naming policy:
322328

323329
### Use a custom JSON property naming policy
324330

325-
Derive from <xref:System.Text.Json.JsonNamingPolicy> and override <xref:System.Text.Json.JsonNamingPolicy.ConvertName*>:
331+
To use a custom JSON property naming policy, create a class that derives from <xref:System.Text.Json.JsonNamingPolicy> and override the <xref:System.Text.Json.JsonNamingPolicy.ConvertName%2A> method, as shown in the following example:
326332

327333
```csharp
328334
class UpperCaseNamingPolicy : JsonNamingPolicy
@@ -334,7 +340,7 @@ class UpperCaseNamingPolicy : JsonNamingPolicy
334340
}
335341
```
336342

337-
Set <xref:System.Text.Json.JsonSerializerOptions.PropertyNamingPolicy> to an instance of your naming policy class:
343+
Then set the <xref:System.Text.Json.JsonSerializerOptions.PropertyNamingPolicy?displayProperty=nameWithType> property to an instance of your naming policy class:
338344

339345
```csharp
340346
var options = new JsonSerializerOptions
@@ -373,7 +379,7 @@ The JSON property naming policy:
373379

374380
### Camel case dictionary keys
375381

376-
If a property of an object to be serialized is of type `Dictionary<string,Tvalue>`, the `string` keys can be converted to camel case. To do that, set <xref:System.Text.Json.JsonSerializerOptions.DictionaryKeyPolicy> to `JsonNamingPolicy.CamelCase`:
382+
If a property of an object to be serialized is of type `Dictionary<string,TValue>`, the `string` keys can be converted to camel case. To do that, set <xref:System.Text.Json.JsonSerializerOptions.DictionaryKeyPolicy> to `JsonNamingPolicy.CamelCase`, as shown in the following example:
377383

378384
```csharp
379385
var options = new JsonSerializerOptions
@@ -408,15 +414,15 @@ The camel case naming policy applies to serialization only.
408414

409415
## Exclude properties
410416

411-
This section explains how to exclude:
417+
By default, all public properties are serialized. If you don't want some of them to appear in the JSON output, you have several options. This section explains how to exclude:
412418

413419
* Individual properties
414420
* All read-only properties
415421
* All null-value properties
416422

417423
### Exclude individual properties
418424

419-
Use the [[JsonIgnore]](xref:System.Text.Json.Serialization.JsonIgnoreAttribute) attribute.
425+
To ignore individual properties, use the [[JsonIgnore]](xref:System.Text.Json.Serialization.JsonIgnoreAttribute) attribute.
420426

421427
Here's an example type to serialize and JSON output:
422428

@@ -441,7 +447,7 @@ class WeatherForecast
441447

442448
### Exclude all read-only properties
443449

444-
Set <xref:System.Text.Json.JsonSerializerOptions.IgnoreReadOnlyProperties> to true:
450+
To exclude all read-only properties, set the <xref:System.Text.Json.JsonSerializerOptions.IgnoreReadOnlyProperties?displayProperty=nameWithType> to `true`, as shown in the following example:
445451

446452
```csharp
447453
var options = new JsonSerializerOptions
@@ -475,7 +481,7 @@ This option applies only to serialization. During deserialization, read-only pro
475481

476482
### Exclude all null value properties
477483

478-
Set <xref:System.Text.Json.JsonSerializerOptions.IgnoreNullValues> to true:
484+
To exclude all null value properties, set the <xref:System.Text.Json.JsonSerializerOptions.IgnoreNullValues> property to `true`, as shown in the following example:
479485

480486
```csharp
481487
var options = new JsonSerializerOptions
@@ -500,11 +506,11 @@ Here's an example object to serialize and JSON output:
500506
}
501507
```
502508

503-
This setting applies to serialization and deserialization. During deserialization, null values in the JSON are ignored only if they are valid. [Null values for non-nullable value types cause exceptions](https://github.com/dotnet/corefx/issues/40922).
509+
This setting applies to serialization and deserialization. During deserialization, null values in the JSON are ignored only if they are valid. Null values for non-nullable value types cause exceptions. For more information, see the [issue on non-nullable value types](https://github.com/dotnet/corefx/issues/40922) in the dotnet/corefx repository on GitHub.
504510

505511
## Case-insensitive property matching
506512

507-
By default, deserialization looks for case-sensitive property name matches between JSON and the target object properties. To change that behavior, set <xref:System.Text.Json.JsonSerializerOptions.PropertyNameCaseInsensitive> to true:
513+
By default, deserialization looks for case-sensitive property name matches between JSON and the target object properties. To change that behavior, set the <xref:System.Text.Json.JsonSerializerOptions.PropertyNameCaseInsensitive?displayProperty=nameWithType> to `true`:
508514

509515
```csharp
510516
var options = new JsonSerializerOptions
@@ -576,7 +582,7 @@ This behavior is intended to help prevent accidental exposure of data in a deriv
576582

577583
To serialize the properties of the derived type, use one of the following approaches:
578584

579-
* Call an overload of `Serialize` that lets you specify the type at runtime:
585+
* Call an overload of <xref:System.Text.Json.JsonSerializer.Serialize%2A> that lets you specify the type at runtime:
580586

581587
```csharp
582588
json = JsonSerializer.Serialize(weatherForecast, weatherForecast.GetType());
@@ -707,7 +713,12 @@ using (var stream = new MemoryStream())
707713
The following example shows how to use the <xref:System.Text.Json.Utf8JsonReader> class directly. The code assumes that the `jsonUtf8` variable is a byte array that contains valid JSON, encoded as UTF-8.
708714

709715
```csharp
710-
Utf8JsonReader reader = new Utf8JsonReader(jsonUtf8, isFinalBlock: true, state: default);
716+
var options = new JsonReaderOptions
717+
{
718+
AllowTrailingCommas = true,
719+
CommentHandling = JsonCommentHandling.Skip
720+
};
721+
Utf8JsonReader reader = new Utf8JsonReader(jsonUtf8, options);
711722

712723
while (reader.Read())
713724
{

docs/standard/serialization/system-text-json-overview.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
---
22
title: "JSON serialization in .NET"
3-
ms.date: "09/02/2019"
3+
author: tdykstra
4+
ms.author: tdykstra
5+
ms.date: "09/16/2019"
46
helpviewer_keywords:
57
- "JSON serialization"
68
- "serializing objects"

0 commit comments

Comments
 (0)