You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/standard/serialization/system-text-json-how-to.md
+52-41Lines changed: 52 additions & 41 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,8 @@
1
1
---
2
2
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"
4
6
helpviewer_keywords:
5
7
- "JSON serialization"
6
8
- "serializing objects"
@@ -17,7 +19,7 @@ This article shows how to use the <xref:System.Text.Json> namespace to serialize
17
19
18
20
## Namespaces
19
21
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:
21
23
22
24
```csharp
23
25
usingSystem.Text.Json;
@@ -28,14 +30,18 @@ Attributes from the <xref:System.Runtime.Serialization> namespace aren't current
28
30
29
31
## How to write .NET objects to JSON (serialize)
30
32
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:
@@ -122,29 +128,29 @@ As an alternative, a <xref:System.Text.Json.JsonSerializer.Serialize%2A> overloa
122
128
123
129
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).
124
130
125
-
## Default serialization behavior
131
+
## Serialization behavior
126
132
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.
133
139
134
140
Supported types include:
135
141
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.
137
143
* User-defined [Plain Old CLR Objects (POCOs)](https://stackoverflow.com/questions/250001/poco-definition).
138
144
* One-dimensional and jagged arrays (`ArrayName[][]`).
139
145
*`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.
141
147
*<xref:System.Collections>
142
148
*<xref:System.Collections.Generic>
143
149
*<xref:System.Collections.Immutable>
144
150
145
151
## How to read JSON into .NET objects (deserialize)
146
152
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:
148
154
149
155
```csharp
150
156
stringjson=... ;
@@ -158,36 +164,36 @@ Overloads of <xref:System.Text.Json.JsonSerializer.Deserialize*> let you deseria
158
164
159
165
### Deserialize from UTF-8
160
166
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:
*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).
180
186
* If the JSON contains a value for a read-only property, the value is ignored and no exception is thrown.
181
187
* 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.
184
190
* 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.
186
192
* The [default maximum depth](xref:System.Text.Json.JsonReaderOptions.MaxDepth) is 64.
187
193
188
194
## Serialize to formatted JSON
189
195
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`:
191
197
192
198
```csharp
193
199
varoptions=newJsonSerializerOptions
@@ -218,7 +224,7 @@ class WeatherForecast
218
224
219
225
## Allow comments and trailing commas
220
226
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:
222
228
223
229
```csharp
224
230
varoptions=newJsonSerializerOptions
@@ -241,14 +247,14 @@ Here's example JSON with comments and a trailing comma:
241
247
242
248
## Customize JSON names
243
249
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:
245
251
246
252
* Customize individual property names
247
253
* Convert all property names to camel case
248
254
* Implement a custom property naming policy
249
255
* Convert dictionary keys to camel case
250
256
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.
252
258
253
259
### Customize individual property names
254
260
@@ -283,7 +289,7 @@ The property name set by this attribute:
283
289
284
290
### Use camel case for all JSON property names
285
291
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:
287
293
288
294
```csharp
289
295
varoptions=newJsonSerializerOptions
@@ -322,7 +328,7 @@ The camel case property naming policy:
322
328
323
329
### Use a custom JSON property naming policy
324
330
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:
326
332
327
333
```csharp
328
334
classUpperCaseNamingPolicy : JsonNamingPolicy
@@ -334,7 +340,7 @@ class UpperCaseNamingPolicy : JsonNamingPolicy
334
340
}
335
341
```
336
342
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:
338
344
339
345
```csharp
340
346
varoptions=newJsonSerializerOptions
@@ -373,7 +379,7 @@ The JSON property naming policy:
373
379
374
380
### Camel case dictionary keys
375
381
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:
377
383
378
384
```csharp
379
385
varoptions=newJsonSerializerOptions
@@ -408,15 +414,15 @@ The camel case naming policy applies to serialization only.
408
414
409
415
## Exclude properties
410
416
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:
412
418
413
419
* Individual properties
414
420
* All read-only properties
415
421
* All null-value properties
416
422
417
423
### Exclude individual properties
418
424
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.
420
426
421
427
Here's an example type to serialize and JSON output:
422
428
@@ -441,7 +447,7 @@ class WeatherForecast
441
447
442
448
### Exclude all read-only properties
443
449
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:
445
451
446
452
```csharp
447
453
varoptions=newJsonSerializerOptions
@@ -475,7 +481,7 @@ This option applies only to serialization. During deserialization, read-only pro
475
481
476
482
### Exclude all null value properties
477
483
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:
479
485
480
486
```csharp
481
487
varoptions=newJsonSerializerOptions
@@ -500,11 +506,11 @@ Here's an example object to serialize and JSON output:
500
506
}
501
507
```
502
508
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.
504
510
505
511
## Case-insensitive property matching
506
512
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`:
508
514
509
515
```csharp
510
516
varoptions=newJsonSerializerOptions
@@ -576,7 +582,7 @@ This behavior is intended to help prevent accidental exposure of data in a deriv
576
582
577
583
To serialize the properties of the derived type, use one of the following approaches:
578
584
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:
@@ -707,7 +713,12 @@ using (var stream = new MemoryStream())
707
713
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.
0 commit comments