- C# Json Serializer
- Serialize Object To Json File C#
- Serialize Object To Json Jackson
- Serialize Object To Json Typescript
- Serialize Object To Json File
Jan 04, 2018 Use JSON to serialize and deserialize objects in C#. That attribute is defined in the System.Runtime.Serialization namespace, so the code includes a using directive to make using that namespace easier. To use the namespace, you also need to add a reference to System.Runtime.Serialization at design time. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom.Net object. In the following code, it calls static method DeserializeObject of JsonConvert class by passing JSON data. It returns custom object (BlogSites) from JSON data. The serialized data is suitable for storage in files and databases, and can be sent to other computer systems across network protocols. In this short tutorial, you will see how to use features built-in to the.NET framework to serialize objects to JavaScript object notation (JSON).
JSON (JavaScript Object Notation) is an efficient data encoding format that enables fast exchanges of small amounts of data between client browsers and AJAX-enabled Web services.
Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. SerializeObject(Object, Type, Formatting, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. It handles missing json properties quite well (it will automatically convert to nullable types when it recognises properties not repeated in the arrays of objects). Of course having a c# converter class would not make sense if the json was completely irregular/randomic. In those situations, using dynamic is the way to go.
This article demonstrates how to serialize .NET type objects into JSON-encoded data and then deserialize data in the JSON format back into instances of .NET types. This example uses a data contract to demonstrate serialization and deserialization of a user-defined
Person
type and uses DataContractJsonSerializer.Normally, JSON serialization and deserialization are handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints. However, in some cases you may need to work with JSON data directly.
Note
This article is about DataContractJsonSerializer. For most scenarios that involve serializing and deserializing JSON, we recommend the tools in the System.Text.Json namespace.
This article is based on the DataContractJsonSerializer sample.
To define the data contract for a Person type
- Define the data contract for
Person
by attaching the DataContractAttribute to the class and DataMemberAttribute attribute to the members you want to serialize. For more information about data contracts, see Designing service contracts.
To serialize an instance of type Person to JSON
Note
If an error occurs during serialization of an outgoing reply on the server or for some other reason, it may not get returned to the client as a fault.
- Create an instance of the
Person
type. - Serialize the
Person
object to a memory stream by using the DataContractJsonSerializer. - Use the WriteObject method to write JSON data to the stream.
- Show the JSON output.
To deserialize an instance of type Person from JSON
- Deserialize the JSON-encoded data into a new instance of
Person
by using the ReadObject method of the DataContractJsonSerializer. - Show the results.
Example
Note
The JSON serializer throws a serialization exception for data contracts that have multiple members with the same name, as shown in the following sample code.
See also
-->Important
The JSON serialization documentation is under construction. This article doesn't cover all scenarios. For more information, examine System.Text.Json issues in the dotnet/corefx repository on GitHub, especially those labeled json-functionality-doc.
This article shows how to use the System.Text.Json namespace to serialize and deserialize to and from JavaScript Object Notation (JSON). The directions and sample code use the library directly, not through a framework such as ASP.NET Core.
Namespaces
The System.Text.Json namespace contains all the entry points and the main types. The 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:Attributes from the System.Runtime.Serialization namespace aren't currently supported in
System.Text.Json
.How to write .NET objects to JSON (serialize)
To write JSON to a string, call the JsonSerializer.Serialize method. The following example uses an overload with a generic type parameter:
You can omit the generic type parameter and use generic type inference instead:
Here's an example type to be serialized, which contains collections and nested classes:
The JSON output is minified by default:
The following example shows the same JSON, formatted (that is, pretty-printed with whitespace and indentation):
Overloads of Serialize let you serialize to a Stream. Async versions of the
Stream
overloads are available.Serialize to UTF-8
To serialize to UTF-8, call the JsonSerializer.SerializeToUtf8Bytes method:
As an alternative, a Serialize overload that takes a Utf8JsonWriter is available.
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).
Serialization behavior
- By default, all public properties are serialized. You can specify properties to exclude.
- The default encoder escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to the JSON spec.
- By default, JSON is minified. You can pretty-print the JSON.
- By default, casing of JSON names matches the .NET names. You can customize JSON name casing.
- Circular references are detected and exceptions thrown. For more information, see the issue on circular references in the dotnet/corefx repository on GitHub.
- Currently, fields are excluded.
Supported types include:
- .NET primitives that map to JavaScript primitives, such as numeric types, strings, and Boolean.
- User-defined Plain Old CLR Objects (POCOs).
- One-dimensional and jagged arrays (
ArrayName[][]
). Dictionary<string,TValue>
whereTValue
isobject
,JsonElement
, or a POCO.- Collections from the following namespaces. For more information, see the issue on collection support in the dotnet/corefx repository on GitHub.
How to read JSON into .NET objects (deserialize)
To deserialize from a string, call the JsonSerializer.Deserialize method, as shown in the following example:
For an example, see the serialize section. The JSON and .NET object are the same, but the direction is reversed.
Overloads of Deserialize let you deserialize from a
Stream
. Async versions of the Stream
overloads are available.Deserialize from UTF-8
To deserialize from UTF-8, call a JsonSerializer.Deserialize overload that takes a
Utf8JsonReader
or a ReadOnlySpan<byte>
, as shown in the following examples:Deserialization behavior
- By default, property name matching is case-sensitive. You can specify case-insensitivity.
- If the JSON contains a value for a read-only property, the value is ignored and no exception is thrown.
- Deserialization to reference types without a parameterless constructor isn't supported.
- Deserialization to immutable objects or read-only properties isn't supported. For more information, see the GitHub issue on immutable object support and the issue on read-only property support in the dotnet/corefx repository on GitHub.
- By default, enums are supported as numbers.
- Fields aren't supported.
- By default, comments or trailing commas in the JSON throw exceptions. You can allow comments and trailing commas if needed.
- The default maximum depth is 64.
Serialize to formatted JSON
To pretty-print the JSON output, set JsonSerializerOptions.WriteIndented to
true
:Here's an example type to be serialized and JSON output:
Allow comments and trailing commas
By default comments and trailing commas are not allowed in JSON. To allow comments in the JSON, set the JsonSerializerOptions.ReadCommentHandling property to
JsonCommentHandling.Skip
. And to allow trailing commas, set the JsonSerializerOptions.AllowTrailingCommas property to true
. The following example shows how to allow both:Here's example JSON with comments and a trailing comma:
Customize JSON names
By default, property names and dictionary keys are unchanged in the JSON output, including case. This section explains how to:
- Customize individual property names
- Convert all property names to camel case
- Implement a custom property naming policy
- Convert dictionary keys to camel case
Currently, there's no support for automatically converting enums to camel case. For more information, see the issue on enum camel case support in the dotnet/corefx repository on GitHub.
Customize individual property names
To set the name of individual properties, use the [JsonPropertyName] attribute.
Here's an example type to serialize and resulting JSON:
The property name set by this attribute:
- Applies in both directions, for serialization and deserialization.
- Takes precedence over property naming policies.
Use camel case for all JSON property names
To use camel case for all JSON property names, set JsonSerializerOptions.PropertyNamingPolicy to
JsonNamingPolicy.CamelCase
, as shown in the following example:Here's an example class to serialize and JSON output:
The camel case property naming policy:
- Applies to serialization and deserialization.
- Is overridden by
[JsonPropertyName]
attributes.
Use a custom JSON property naming policy
To use a custom JSON property naming policy, create a class that derives from JsonNamingPolicy and override the ConvertName method, as shown in the following example:
Then set the JsonSerializerOptions.PropertyNamingPolicy property to an instance of your naming policy class:
Here's an example class to serialize and JSON output:
The JSON property naming policy:
- Applies to serialization and deserialization.
- Is overridden by
[JsonPropertyName]
attributes.
Camel case dictionary keys
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 DictionaryKeyPolicy to JsonNamingPolicy.CamelCase
, as shown in the following example:Here's an example object to serialize and JSON output:
Property | Value |
---|---|
Date | 8/1/2019 12:00:00 AM -07:00 |
TemperatureC | 25 |
Summary | Hot |
TemperatureRanges | Cold, 20 Hot, 40 |
The camel case naming policy applies to serialization only.
Exclude properties
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:
- Individual properties
- All read-only properties
- All null-value properties
Exclude individual properties
To ignore individual properties, use the [JsonIgnore] attribute.
Here's an example type to serialize and JSON output:
Exclude all read-only properties
To exclude all read-only properties, set the JsonSerializerOptions.IgnoreReadOnlyProperties to
true
, as shown in the following example:Here's an example type to serialize and JSON output:
C# Json Serializer
This option applies only to serialization. During deserialization, read-only properties are ignored by default. A property is read-only if it contains a public getter but not a public setter.
Serialize Object To Json File C#
Exclude all null value properties
To exclude all null value properties, set the IgnoreNullValues property to
true
, as shown in the following example:Here's an example object to serialize and JSON output:
Property | Value |
---|---|
Date | 8/1/2019 12:00:00 AM -07:00 |
TemperatureC | 25 |
Summary | null |
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 in the dotnet/corefx repository on GitHub.
Case-insensitive property matching
By default, deserialization looks for case-sensitive property name matches between JSON and the target object properties. To change that behavior, set the JsonSerializerOptions.PropertyNameCaseInsensitive to
true
:Here's example JSON with camel case property names. It can be deserialized into the following type that has Pascal case property names.
Include properties of derived classes
Polymorphic serialization isn't supported when you specify at compile time the type to be serialized. For example, suppose you have a
WeatherForecast
class and a derived class WeatherForecastWithWind
:And suppose the type passed to, or inferred by, the
Serialize
method at compile time is WeatherForecast
:In this scenario, the
WindSpeed
property is not serialized even if the weatherForecast
object is actually a WeatherForecastWithWind
object. Only the base class properties are serialized:This behavior is intended to help prevent accidental exposure of data in a derived runtime-created type.
To serialize the properties of the derived type, use one of the following approaches:
- Call an overload of Serialize that lets you specify the type at runtime:
- Declare the object to be serialized as
object
.
In the preceding example scenario, both approaches cause the
WindSpeed
property to be included in the JSON output:Handle overflow JSON
While deserializing, you might receive data in the JSON that is not represented by properties of the target type. For example, suppose your target type is this:
And the JSON to be deserialized is this:
If you deserialize the JSON shown into the type shown, the
DatesAvailable
and SummaryWords
properties have nowhere to go and are lost. To capture extra data such as these properties, apply the JsonExtensionData attribute to a property of type Dictionary<string,object>
or Dictionary<string,JsonElement>
:Serialize Object To Json Jackson
When you deserialize the JSON shown earlier into this sample type, the extra data becomes key-value pairs of the
ExtensionData
property:Property | Value | Notes |
---|---|---|
Date | 8/1/2019 12:00:00 AM -07:00 | |
TemperatureC | 0 | Case-sensitive mismatch (temperatureC in the JSON), so the property isn't set. |
Summary | Hot | |
ExtensionData | temperatureC: 25 | Since the case didn't match, this JSON property is an extra and becomes a key-value pair in the dictionary. |
DatesAvailable: 8/1/2019 12:00:00 AM -07:00 8/2/2019 12:00:00 AM -07:00 | Extra property from the JSON becomes a key-value pair, with an array as the value object. | |
SummaryWords: Cool Windy Humid | Extra property from the JSON becomes a key-value pair, with an array as the value object. |
When the target object is serialized, the extension data key value pairs become JSON properties just as they were in the incoming JSON:
Notice that the
ExtensionData
property name doesn't appear in the JSON. This behavior lets the JSON make a round trip without losing any extra data that otherwise wouldn't be deserialized.Use Utf8JsonWriter directly
The following example shows how to use the Utf8JsonWriter class directly.
Use Utf8JsonReader directly
Serialize Object To Json Typescript
The following example shows how to use the Utf8JsonReader class directly. The code assumes that the
jsonUtf8
variable is a byte array that contains valid JSON, encoded as UTF-8.