The System.Text.Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). The System.Text.Json library is included in the runtime for .NET Core 3.1 and later versions. For other target frameworks, install the System.Text.Json NuGet package. The package supports:
System.Text.Json focuses primarily on performance, security, and standards compliance. It has some key differences in default behavior and doesn't aim to have feature parity with Newtonsoft.Json. For some scenarios, System.Text.Json currently has no built-in functionality, but there are recommended workarounds. For other scenarios, workarounds are impractical.
The System.Text.Json team is investing in adding the features that are most often requested. If your application depends on a missing feature, consider filing an issue in the dotnet/runtime GitHub repository to find out if support for your scenario can be added.
Most of this article is about how to use the JsonSerializer API, but it also includes guidance on how to use the JsonDocument (which represents the Document Object Model or DOM), Utf8JsonReader, and Utf8JsonWriter types.
In Visual Basic, you can't use Utf8JsonReader, which also means you can't write custom converters. Most of the workarounds presented here require that you write custom converters. You can write a custom converter in C# and register it in a Visual Basic project. For more information, see Visual Basic support.
Table of differences
The following table lists Newtonsoft.Json features and System.Text.Json equivalents. The equivalents fall into the following categories:
✔️ Supported by built-in functionality. Getting similar behavior from System.Text.Json might require the use of an attribute or global option.
⚠️ Not supported, but workaround is possible. The workarounds are custom converters, which might not provide complete parity with Newtonsoft.Json functionality. For some of these, sample code is provided as examples. If you rely on these Newtonsoft.Json features, migration will require modifications to your .NET object models or other code changes.
❌ Not supported, and workaround is not practical or possible. If you rely on these Newtonsoft.Json features, migration will not be possible without significant changes.
This is not an exhaustive list of Newtonsoft.Json features. The list includes many of the scenarios that have been requested in GitHub issues or StackOverflow posts. If you implement a workaround for one of the scenarios listed here that doesn't currently have sample code, and if you want to share your solution, select This page in the Feedback section at the bottom of this page. That creates an issue in this documentation's GitHub repo and lists it in the Feedback section on this page too.
Differences in default behavior
System.Text.Json is strict by default and avoids any guessing or interpretation on the caller's behalf, emphasizing deterministic behavior. The library is intentionally designed this way for performance and security. Newtonsoft.Json is flexible by default. This fundamental difference in design is behind many of the following specific differences in default behavior.
Case-insensitive deserialization
During deserialization, Newtonsoft.Json does case-insensitive property name matching by default. The System.Text.Json default is case-sensitive, which gives better performance since it's doing an exact match. For information about how to do case-insensitive matching, see Case-insensitive property matching.
If you're using System.Text.Json indirectly by using ASP.NET Core, you don't need to do anything to get behavior like Newtonsoft.Json. ASP.NET Core specifies the settings for camel-casing property names and case-insensitive matching when it uses System.Text.Json.
ASP.NET Core also enables deserializing quoted numbers by default.
Minimal character escaping
During serialization, Newtonsoft.Json is relatively permissive about letting characters through without escaping them. That is, it doesn't replace them with \uxxxx where xxxx is the character's code point. Where it does escape them, it does so by emitting a \ before the character (for example, " becomes \"). System.Text.Json escapes more characters by default to provide defense-in-depth protections against cross-site scripting (XSS) or information-disclosure attacks and does so by using the six-character sequence. System.Text.Json escapes all non-ASCII characters by default, so you don't need to do anything if you're using StringEscapeHandling.EscapeNonAscii in Newtonsoft.Json. System.Text.Json also escapes HTML-sensitive characters, by default. For information about how to override the default System.Text.Json behavior, see Customize character encoding.
Comments
During deserialization, Newtonsoft.Json ignores comments in the JSON by default. The System.Text.Json default is to throw exceptions for comments because the RFC 8259 specification doesn't include them. For information about how to allow comments, see Allow comments and trailing commas.
Trailing commas
During deserialization, Newtonsoft.Json ignores trailing commas by default. It also ignores multiple trailing commas (for example, [{"Color":"Red"},{"Color":"Green"},,]). The System.Text.Json default is to throw exceptions for trailing commas because the RFC 8259 specification doesn't allow them. For information about how to make System.Text.Json accept them, see Allow comments and trailing commas. There's no way to allow multiple trailing commas.
Converter registration precedence
The Newtonsoft.Json registration precedence for custom converters is as follows:
This order means that a custom converter in the Converters collection is overridden by a converter that is registered by applying an attribute at the type level. Both of those registrations are overridden by an attribute at the property level.
The System.Text.Json registration precedence for custom converters is different:
The difference here is that a custom converter in the Converters collection overrides an attribute at the type level. The intention behind this order of precedence is to make run-time changes override design-time choices. There's no way to change the precedence.
The latest version of Newtonsoft.Json has a maximum depth limit of 64 by default. System.Text.Json also has a default limit of 64, and it's configurable by setting JsonSerializerOptions.MaxDepth.
If you're using System.Text.Json indirectly by using ASP.NET Core, the default maximum depth limit is 32. The default value is the same as for model binding and is set in the JsonOptions class.
JSON strings (property names and string values)
During deserialization, Newtonsoft.Json accepts property names surrounded by double quotes, single quotes, or without quotes. It accepts string values surrounded by double quotes or single quotes. For example, Newtonsoft.Json accepts the following JSON:
System.Text.Json only accepts property names and string values in double quotes because that format is required by the RFC 8259 specification and is the only format considered valid JSON.
A value enclosed in single quotes results in a JsonException with the following message:
Output
''' is an invalid start of a value.
Non-string values for string properties
Newtonsoft.Json accepts non-string values, such as a number or the literals true and false, for deserialization to properties of type string. Here's an example of JSON that Newtonsoft.Json successfully deserializes to the following class:
System.Text.Json doesn't deserialize non-string values into string properties. A non-string value received for a string field results in a JsonException with the following message:
Output
The JSON value could not be converted to System.String.
Scenarios using JsonSerializer
Some of the following scenarios aren't supported by built-in functionality, but workarounds are possible. The workarounds are custom converters, which may not provide complete parity with Newtonsoft.Json functionality. For some of these, sample code is provided as examples. If you rely on these Newtonsoft.Json features, migration will require modifications to your .NET object models or other code changes.
For some of the following scenarios, workarounds are not practical or possible. If you rely on these Newtonsoft.Json features, migration will not be possible without significant changes.
If you're using System.Text.Json indirectly by using ASP.NET Core, you don't need to do anything to get behavior like Newtonsoft.Json. ASP.NET Core specifies web defaults when it uses System.Text.Json, and web defaults allow quoted numbers.
Newtonsoft.Json has several ways to conditionally ignore a property on serialization or deserialization:
DefaultContractResolver lets you select properties to include or ignore, based on arbitrary criteria.
The NullValueHandling and DefaultValueHandling settings on JsonSerializerSettings let you specify that all null-value or default-value properties should be ignored.
The NullValueHandling and DefaultValueHandling settings on the [JsonProperty] attribute let you specify individual properties that should be ignored when set to null or the default value.
System.Text.Json provides the following ways to ignore properties or fields while serializing:
The [JsonIgnore] attribute on a property causes the property to be omitted from the JSON during serialization.
In addition, in .NET 7 and later versions, you can customize the JSON contract to ignore properties based on arbitrary criteria. For more information, see Custom contracts.
Public and non-public fields
Newtonsoft.Json can serialize and deserialize fields as well as properties.
By default, Newtonsoft.Json serializes by value. For example, if an object contains two properties that contain a reference to the same Person object, the values of that Person object's properties are duplicated in the JSON.
Newtonsoft.Json has a PreserveReferencesHandling setting on JsonSerializerSettings that lets you serialize by reference:
An identifier metadata is added to the JSON created for the first Person object.
The JSON that is created for the second Person object contains a reference to that identifier instead of property values.
Newtonsoft.Json also has a ReferenceLoopHandling setting that lets you ignore circular references rather than throw an exception.
To preserve references and handle circular references in System.Text.Json, set JsonSerializerOptions.ReferenceHandler to Preserve. The ReferenceHandler.Preserve setting is equivalent to PreserveReferencesHandling = PreserveReferencesHandling.All in Newtonsoft.Json.
The ReferenceHandler.IgnoreCycles option has behavior similar to Newtonsoft.Json ReferenceLoopHandling.Ignore. One difference is that the System.Text.Json implementation replaces reference loops with the null JSON token instead of ignoring the object reference. For more information, see Ignore circular references.
Both Newtonsoft.Json and System.Text.Json support collections of type Dictionary<TKey, TValue>. For information about supported key types, see Supported key types.
Caution
Deserializing to a Dictionary<TKey, TValue> where TKey is typed as anything other than string could introduce a security vulnerability in the consuming application. For more information, see dotnet/runtime#4761.
Types without built-in support
System.Text.Json doesn't provide built-in support for the following types:
Newtonsoft.Json has a TypeNameHandling setting that adds type-name metadata to the JSON while serializing. It uses the metadata while deserializing to do polymorphic deserialization. Starting in .NET 7, System.Text.Json relies on type discriminator information to perform polymorphic deserialization. This metadata is emitted in the JSON and then used during deserialization to determine whether to deserialize to the base type or a derived type. For more information, see Serialize properties of derived classes.
To support polymorphic deserialization in older .NET versions, create a converter like the example in How to write custom converters.
Deserialize string enum values
By default, System.Text.Json doesn't support deserializing string enum values, whereas Newtonsoft.Json does. For example, the following code throws a JsonException:
C#
string json = "{ \"Text\": \"Hello\", \"Enum\": \"Two\" }";
var _ = JsonSerializer.Deserialize<MyObj>(json); // Throws exception.classMyObj
{
publicstring Text { get; set; } = "";
public MyEnum Enum { get; set; }
}
enum MyEnum
{
One,
Two,
Three
}
Infers the type of primitive values in the JSON payload (other than null) and returns the stored string, long, double, boolean, or DateTime as a boxed object. Primitive values are single JSON values such as a JSON number, string, true, false, or null.
Returns a JObject or JArray for complex values in the JSON payload. Complex values are collections of JSON key-value pairs within braces ({}) or lists of values within brackets ([]). The properties and values within the braces or brackets can have additional properties or values.
Returns a null reference when the payload has the null JSON literal.
System.Text.Json stores a boxed JsonElement for both primitive and complex values whenever deserializing to Object, for example:
An object property.
An object dictionary value.
An object array value.
A root object.
However, System.Text.Json treats null the same as Newtonsoft.Json and returns a null reference when the payload has the null JSON literal in it.
To implement type inference for object properties, create a converter like the example in How to write custom converters.
Deserialize null to non-nullable type
Newtonsoft.Json doesn't throw an exception in the following scenario:
NullValueHandling is set to Ignore, and
During deserialization, the JSON contains a null value for a non-nullable value type.
Note: The preceding converter handles null values differently than Newtonsoft.Json does for POCOs that specify default values. For example, suppose the following code represents your target object:
C#
publicclassWeatherForecastWithDefault
{
publicWeatherForecastWithDefault()
{
Date = DateTimeOffset.Parse("2001-01-01");
Summary = "No summary";
}
public DateTimeOffset Date { get; set; }
publicint TemperatureCelsius { get; set; }
publicstring Summary { get; set; }
}
And suppose the following JSON is deserialized by using the preceding converter:
After deserialization, the Date property has 1/1/0001 (default(DateTimeOffset)), that is, the value set in the constructor is overwritten. Given the same POCO and JSON, Newtonsoft.Json deserialization would leave 1/1/2001 in the Date property.
Deserialize to immutable classes and structs
Newtonsoft.Json can deserialize to immutable classes and structs because it can use constructors that have parameters.
In Newtonsoft.Json, you specify that a property is required by setting Required on the [JsonProperty] attribute. Newtonsoft.Json throws an exception if no value is received in the JSON for a property marked as required.
Starting in .NET 7, you can use the C# required modifier or the JsonRequiredAttribute attribute on a required property. System.Text.Json throws an exception if the JSON payload doesn't contain a value for the marked property. For more information, see Required properties.
Specify date format
Newtonsoft.Json provides several ways to control how properties of DateTime and DateTimeOffset types are serialized and deserialized:
The DateTimeZoneHandling setting can be used to serialize all DateTime values as UTC dates.
The DateFormatString setting and DateTime converters can be used to customize the format of date strings.
System.Text.Json supports ISO 8601-1:2019, including the RFC 3339 profile. This format is widely adopted, unambiguous, and makes round trips precisely. To use any other format, create a custom converter. For example, the following converters serialize and deserialize JSON that uses Unix epoch format with or without a time zone offset (values such as /Date(1590863400000-0700)/ or /Date(1590863400000)/):
Newtonsoft.Json lets you execute custom code at several points in the serialization or deserialization process:
OnDeserializing (when beginning to deserialize an object)
OnDeserialized (when finished deserializing an object)
OnSerializing (when beginning to serialize an object)
OnSerialized (when finished serializing an object)
System.Text.Json exposes the same notifications during serialization and deserialization. To use them, implement one or more of the following interfaces from the System.Text.Json.Serialization namespace:
The OnDeserializing code doesn't have access to the new POCO instance. To manipulate the new POCO instance at the start of deserialization, put that code in the POCO constructor.
Non-public property setters and getters
Newtonsoft.Json can use private and internal property setters and getters via the JsonProperty attribute.
The JsonConvert.PopulateObject method in Newtonsoft.Json deserializes a JSON document to an existing instance of a class, instead of creating a new instance. System.Text.Json always creates a new instance of the target type by using the default public parameterless constructor. Custom converters can deserialize to an existing instance.
Reuse rather than replace properties
Starting in .NET 8, System.Text.Json supports reusing initialized properties rather than replacing them. There are some differences in behavior, which you can read about in the API proposal.
Starting in .NET 8, System.Text.Json supports populating properties, including those that don't have a setter. For more information, see Populate initialized properties.
Snake case naming policy
System.Text.Json includes a built-in naming policy for snake case. However, there are some behavior differences with Newtonsoft.Json for some inputs. The following table shows some of these differences when converting input using the JsonNamingPolicy.SnakeCaseLower policy.
System.Text.Json doesn't have built-in support for these attributes. However, starting in .NET 7, you can use a custom type resolver to add support. For a sample, see ZCS.DataContractResolver.
Octal numbers
Newtonsoft.Json treats numbers with a leading zero as octal numbers. System.Text.Json doesn't allow leading zeroes because the RFC 8259 specification doesn't allow them.
Handle missing members
If the JSON that's being deserialized includes properties that are missing in the target type, Newtonsoft.Json can be configured to throw exceptions. By default, System.Text.Json ignores extra properties in the JSON, except when you use the [JsonExtensionData] attribute.
In .NET 8 and later versions, you can set your preference for whether to skip or disallow unmapped JSON properties using one of the following means:
Newtonsoft.Json has an attribute, JsonObjectAttribute, that can be applied at the type level to control which members are serialized, how null values are handled, and whether all members are required. System.Text.Json has no equivalent attribute that can be applied on a type. For some behaviors, such as null value handling, you can either configure the same behavior on the global JsonSerializerOptions or individually on each property.
Consider the following example that uses Newtonsoft.Json.JsonObjectAttribute to specify that all null properties should be ignored:
You can achieve the same behavior in System.Text.Json by adding the C# required modifier or the JsonRequiredAttributeto each property. For more information, see Required properties.
C#
publicclassPerson
{
[JsonRequired]
publicstring? Name { get; set; }
public required int? Age { get; set; }
}
TraceWriter
Newtonsoft.Json lets you debug by using a TraceWriter to view logs that are generated by serialization or deserialization. System.Text.Json doesn't do logging.
JsonDocument and JsonElement compared to JToken (like JObject, JArray)
System.Text.Json.JsonDocument provides the ability to parse and build a read-only Document Object Model (DOM) from existing JSON payloads. The DOM provides random access to data in a JSON payload. The JSON elements that compose the payload can be accessed via the JsonElement type. The JsonElement type provides APIs to convert JSON text to common .NET types. JsonDocument exposes a RootElement property.
Starting in .NET 6, you can parse and build a mutable DOM from existing JSON payloads by using the JsonNode type and other types in the System.Text.Json.Nodes namespace. For more information, see Use JsonNode.
JsonDocument is IDisposable
JsonDocument builds an in-memory view of the data into a pooled buffer. Therefore, unlike JObject or JArray from Newtonsoft.Json, the JsonDocument type implements IDisposable and needs to be used inside a using block. For more information, see JsonDocument is IDisposable.
JsonDocument is read-only
The System.Text.Json DOM can't add, remove, or modify JSON elements. It's designed this way for performance and to reduce allocations for parsing common JSON payload sizes (that is, < 1 MB).
JsonElement is a union struct
JsonDocument exposes the RootElement as a property of type JsonElement, which is a union struct type that encompasses any JSON element. Newtonsoft.Json uses dedicated hierarchical types like JObject, JArray, JToken, and so forth. JsonElement is what you can search and enumerate over, and you can use JsonElement to materialize JSON elements into .NET types.
Starting in .NET 6, you can use JsonNode type and types in the System.Text.Json.Nodes namespace that correspond to JObject, JArray, and JToken. For more information, see Use JsonNode.
How to search a JsonDocument and JsonElement for sub-elements
Searches for JSON tokens using JObject or JArray from Newtonsoft.Json tend to be relatively fast because they're lookups in some dictionary. By comparison, searches on JsonElement require a sequential search of the properties and hence are relatively slow (for example when using TryGetProperty). System.Text.Json is designed to minimize initial parse time rather than lookup time. For more information, see How to search a JsonDocument and JsonElement for sub-elements.
The JsonTextReader in Newtonsoft.Json is a class. The Utf8JsonReader type differs in that it's a ref struct. For more information, see ref struct limitations for Utf8JsonReader.
Read null values into nullable value types
Newtonsoft.Json provides APIs that return Nullable<T>, such as ReadAsBoolean, which handles a NullTokenType for you by returning a bool?. The built-in System.Text.Json APIs return only non-nullable value types. For more information, see Read null values into nullable value types.
Multi-target for reading JSON
If you need to continue to use Newtonsoft.Json for certain target frameworks, you can multi-target and have two implementations. However, this is not trivial and would require some #ifdefs and source duplication. One way to share as much code as possible is to create a ref struct wrapper around Utf8JsonReader and Newtonsoft.Json.JsonTextReader. This wrapper would unify the public surface area while isolating the behavioral differences. This lets you isolate the changes mainly to the construction of the type, along with passing the new type around by reference. This is the pattern that the Microsoft.Extensions.DependencyModel library follows:
System.Text.Json.Utf8JsonWriter is a high-performance way to write UTF-8 encoded JSON text from common .NET types like String, Int32, and DateTime. The writer is a low-level type that can be used to build custom serializers.
JsonTextWriter includes the following settings, for which Utf8JsonWriter has no equivalent:
Indentation - Specifies how many characters to indent. Utf8JsonWriter always indents by 2 characters.
IndentChar - Specifies the character to use for indentation. Utf8JsonWriter always uses whitespace.
QuoteChar - Specifies the character to use to surround string values. Utf8JsonWriter always uses double quotes.
QuoteName - Specifies whether or not to surround property names with quotes. Utf8JsonWriter always surrounds them with quotes.
There are no workarounds that would let you customize the JSON produced by Utf8JsonWriter in these ways.
Write Timespan, Uri, or char values
JsonTextWriter provides WriteValue methods for TimeSpan, Uri, and char values. Utf8JsonWriter doesn't have equivalent methods. Instead, format these values as strings (by calling ToString(), for example) and call WriteStringValue.
Multi-target for writing JSON
If you need to continue to use Newtonsoft.Json for certain target frameworks, you can multi-target and have two implementations. However, this is not trivial and would require some #ifdefs and source duplication. One way to share as much code as possible is to create a wrapper around Utf8JsonWriter and Newtonsoft.Json.JsonTextWriter. This wrapper would unify the public surface area while isolating the behavioral differences. This lets you isolate the changes mainly to the construction of the type. Microsoft.Extensions.DependencyModel library follows:
The decision to exclude TypeNameHandling.All-equivalent functionality from System.Text.Json was intentional. Allowing a JSON payload to specify its own type information is a common source of vulnerabilities in web applications. In particular, configuring Newtonsoft.Json with TypeNameHandling.All allows the remote client to embed an entire executable application within the JSON payload itself, so that during deserialization the web application extracts and runs the embedded code. For more information, see Friday the 13th JSON attacks PowerPoint and Friday the 13th JSON attacks details.
JSON Path queries not supported
The JsonDocument DOM doesn't support querying by using JSON Path.
In a JsonNode DOM, each JsonNode instance has a GetPath method that returns a path to that node. But there is no built-in API to handle queries based on JSON Path query strings.
System.Text.Json sets limits that can't be changed for some values, such as the maximum token size in characters (166 MB) and in base 64 (125 MB). For more information, see JsonConstants in the source code and GitHub issue dotnet/runtime #39953.
You can get coding help from GitHub Copilot to migrate your code from Newtonsoft.Json to System.Text.Json within your IDE. You can customize the prompt per your requirements.
Example prompt for Copilot Chat
Copilot prompt
convert the following code to use System.Text.Json
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2024, 08, 08);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
Console.WriteLine(output);
GitHub Copilot is powered by AI, so surprises and mistakes are possible. For more information, see Copilot FAQs.
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET
feedback
.NET
is an open source project. Select a link to provide feedback:
Learn how to serialize and deserialize JavaScript Object Notation (JSON) strings using the JsonSerializer class, the JsonSerializerOptions class, and Data Transfer Objects.