What’s next for System.Text.Json in .NET 5.0?


Isn't it fun,

to instantly listen to a blog on the go? PLAY !

 
 

next-System

There are many new features and performance improvements in .NET 5.0. No exception was found in System.Text.Json. Many Developers familiar with Newtonsoft.Json have improved performance, reliability and made it easier. In .NET 5.0 the progress that has been made with System.Text.Json and what’s going to come next will discuss about in more details.

Table of Content

Getting the Library

You can install .NET 5.0 for your project requirements is in .NET 5, This provides you System.Text.Json right out of the box, without any other pre-requisites.

If your project requirements in .NET Core 3.x or .NET Framework and .NET Standard compatible library so you can install the latest package System.Text.JsonNuget Package.

If your project requirements in .NET Core 3.x or .NET Framework and .NET Standard compatible library so you can install the latest package System.Text.JsonNuget Package.

What is System.Text.Json?

The System.Text.Json is the built-in JavaScript Object Notation (JSON) serialization library in .NET for converting from .NET object types to a JSON string, and vice versa, supporting UTF-8 text encoding. JsonSerializer library was first added in .NET Core 3.0. It’s a popular type in the library JsonSerializer, which provides the highest level of functionality of processing JSON data.

Example:
 

usingSystem.Text.Json;

namespaceJsonLibary
{
classProgram
    {

     staticvoid Main(string[] args)
        {
            Some obj = new() { Message = "Welcome to Visual Studio" };
            stringjson = JsonSerializer.Serialize(obj);
            Console.WriteLine(json);
            Some secondObject = JsonSerializer.Deserialize("{}");
            Console.WriteLine(secondObject.Message);   
        }
     publicclassSome
        {
            publicstring Message { get; set; }
        }
    }
}

Figure:Output Screen

Support for Quoted Numbers

When you are using .NET Core 3.0, the deserializing number types encoded as JSON strings were not supported by default. You can add a custom converter for each applicable number type which would take control of the serialization and deserialization of the type, and include logic to handle quoted numbers.

There is an opt-in feature to support serializing and deserializing quoted numbers, and named floating-point literals like Nan, Infinity, and, -Infinity in .NET 5.0



Example
 

using System;
usingSystem.Text.Json;
usingSystem.Text.Json.Serialization;

namespaceJsonLibary
{
  classProgram
    {
      publicsealedpartialclassJsonSerializerOptions
        {
           publicJsonNumberHandlingNumberHandling{ get; set; }

        }
        [Flags]
        publicenumJsonNumberHandling :byte
        {
            None = 0x0,
            AllowReadingFromString = 0x1,
            WriteAsString = 0x2,
            AllowNamedFloatingPointLiterals = 0x4
        }

        publicsealedpartialclassJsonNumberHandlingAttribute :JsonAttribute
        {
            publicJsonNumberHandling Handling { get; }

            publicJsonNumberHandlingAttribute(JsonNumberHandling handling)
            {
                Handling = handling;
            }
        }

       publicstaticvoid Main(string[] args)
        {
          var options = newJsonSerializerOptions
            {
              NumberHandling = JsonNumberHandling.AllowReadingFromString | 								 
              JsonNumberHandling.WriteAsString
            };

            string json = @"{""Message"":1,""Data"":""2""}";

            Some @class = JsonSerializer.Deserialize(json, options);
            Console.WriteLine(@class.Message);

            Console.WriteLine(@class.Data);

            json = JsonSerializer.Serialize(@class, options);
            Console.WriteLine(json);

        }
        publicclassSome
        {
            publicstring Message { get; set; }
            publicstring Data { get; set; }
        }
    }
}

Extended support for ignoring default values

When you serializing in .NET Core 3.x, there was only possible to ignore the null value for reference or nullable value-typed properties, the JsonSerilizerOptions.IgnoreNullValues setting was only applicable across an entire input object graph. We have to add support to ignore default values for non-nullable value types, such as int and float. Further, we are now possible to cherry-pick properties and fields to be ignored when default.

Example
 

var options = newJsonSerializerOptions
        {
             DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
        };

           varobj = newyourClass();
           stringjson = JsonSerializer.Serialize(obj, options);
           Console.WriteLine(json);

 publicclassyourClass
        {
           publicintyourInt{ get; set; }

            [JsonIgnore(Condition = JsonIgnoreCondition.Never)]
            publicboolyourBool{ get; set; }

            publicstringyourString{ get; set; }
        }

Here we can see that we have passed the default value JsonIgnoreCondition.WhenWritingDefault in the JsonSerializerOptions class and this class declared with options variable, the JsonIgnoreCondition.WhenWritingDefault is ignoring only null values, but not default values.

After, we put the class name yourClass is declared with a new keyword and it identify with theobj variable.

Then, the obj and options value pass in the JsonSerializer.Serialize method with defined by JSON variable, print the JSON variable with console.WriteLine .

Utility Constructors for JsonSerializerOptions

The JsonSerializerOptions coping the one instance to another instance,so we have added a copy constructor to JsonSerializerOptions which makes this easier for the user.

Example
 

JsonSerializerOptions opt = new()
            {
                Handling = JsonNumberHandling.AllowReadingFromString,
                ignoreCondition = JsonIgnoreCondition.WhenWritingNull,
                Converters = { newJsonStringEnumConverter() }
            };
JsonSerializerOptionsnewOpt = new(opt)
            {
                Handling = JsonNumberHandling.Strict
            };

           Console.WriteLine(newOpt.Handling);

           Console.WriteLine(newOpt.ignoreCondition);

           Console.WriteLine(newOpt.Converters[0]);		

There are some common set of options when processing JSON data in web contexts is to use the camelCase naming policy. You specify case-insensitive matching when deserializing, and allow reading quoted numbers. You have to declare the JsonSerializerDefaults.Webenum value, and a new constructor that takes a JsonSerializerDefaults value, provide an easy way to reuse these options in a consistent way across multiple layers of an application.

Example
 

JsonSerializerOptionsserializerOptions = new (JsonSerializerDefaults.Web);

Console.WriteLine(serializerOptions.PropertyNamingPolicy);

Console.WriteLine(serializerOptions.PropertyNameCaseInsensitive);   

Console.WriteLine(serializerOptions.Handling);

Looking to hire ASP.Net Development Company in USA ?

Your Search ends here.


Performance Improvements

There is a major difference between .NET Core 3.1 and .NET 5, and we have improved performance in the following areas.

  1. Performance improved for collections by serialization and deserialization
  2. Performance improved for small types by serialization and deserialization
  3. Performance improved for case-insensitive and missing-property cases by deserialization.
  4. And performance improved for long JSON strings by serialization.

These above improvements are going to be specifically meaningful for high-performance apps.

Improved Performance for Collections

The significant improvements for large collections made by us. These improvements are characterized in much more detail at dotnet/runtime #2259.

Improved Performance for Small Types

The significant efforts to improve .NET performance in the TechEmpower JSON benchmark in .NET 5.0. The performance when observing work done within the serializer is now ~19% better.

Performance improved for case-insensitive by deserialization

There are most common issues with using JSON is a mismatch of naming conventions with .NET design guidelines. The camelCase is used in JSON properties and the PascalCase is used in .NET properties and fields.

Performance improved for long JSON strings by serialization

When we write relatively large JSON strings using the writer directly, there is ~30% improvement.

Conclusion

In this blog, we have learned about the System.Text.Json in .NET 5.0, and which JSON is better for developers like among Newtonsoft.Json and System.Text.Json. Before introducing .NET Core 3.1, most of the developers were using Newtonsoft.Json. It doesn’t provide many features compare to System.Text.Json.

What’s next for System.Text.Json in .NET 5.0?

next-System

There are many new features and performance improvements in .NET 5.0. No exception was found in System.Text.Json. Many Developers familiar with Newtonsoft.Json have improved performance, reliability and made it easier. In .NET 5.0 the progress that has been made with System.Text.Json and what’s going to come next will discuss about in more details.

Table of Content

Getting the Library

You can install .NET 5.0 for your project requirements is in .NET 5, This provides you System.Text.Json right out of the box, without any other pre-requisites.

If your project requirements in .NET Core 3.x or .NET Framework and .NET Standard compatible library so you can install the latest package System.Text.JsonNuget Package.

If your project requirements in .NET Core 3.x or .NET Framework and .NET Standard compatible library so you can install the latest package System.Text.JsonNuget Package.

What is System.Text.Json?

The System.Text.Json is the built-in JavaScript Object Notation (JSON) serialization library in .NET for converting from .NET object types to a JSON string, and vice versa, supporting UTF-8 text encoding. JsonSerializer library was first added in .NET Core 3.0. It’s a popular type in the library JsonSerializer, which provides the highest level of functionality of processing JSON data.

Example:
 

usingSystem.Text.Json;

namespaceJsonLibary
{
classProgram
    {

     staticvoid Main(string[] args)
        {
            Some obj = new() { Message = "Welcome to Visual Studio" };
            stringjson = JsonSerializer.Serialize(obj);
            Console.WriteLine(json);
            Some secondObject = JsonSerializer.Deserialize("{}");
            Console.WriteLine(secondObject.Message);   
        }
     publicclassSome
        {
            publicstring Message { get; set; }
        }
    }
}

Figure:Output Screen

Support for Quoted Numbers

When you are using .NET Core 3.0, the deserializing number types encoded as JSON strings were not supported by default. You can add a custom converter for each applicable number type which would take control of the serialization and deserialization of the type, and include logic to handle quoted numbers.

There is an opt-in feature to support serializing and deserializing quoted numbers, and named floating-point literals like Nan, Infinity, and, -Infinity in .NET 5.0



Example
 

using System;
usingSystem.Text.Json;
usingSystem.Text.Json.Serialization;

namespaceJsonLibary
{
  classProgram
    {
      publicsealedpartialclassJsonSerializerOptions
        {
           publicJsonNumberHandlingNumberHandling{ get; set; }

        }
        [Flags]
        publicenumJsonNumberHandling :byte
        {
            None = 0x0,
            AllowReadingFromString = 0x1,
            WriteAsString = 0x2,
            AllowNamedFloatingPointLiterals = 0x4
        }

        publicsealedpartialclassJsonNumberHandlingAttribute :JsonAttribute
        {
            publicJsonNumberHandling Handling { get; }

            publicJsonNumberHandlingAttribute(JsonNumberHandling handling)
            {
                Handling = handling;
            }
        }

       publicstaticvoid Main(string[] args)
        {
          var options = newJsonSerializerOptions
            {
              NumberHandling = JsonNumberHandling.AllowReadingFromString | 								 
              JsonNumberHandling.WriteAsString
            };

            string json = @"{""Message"":1,""Data"":""2""}";

            Some @class = JsonSerializer.Deserialize(json, options);
            Console.WriteLine(@class.Message);

            Console.WriteLine(@class.Data);

            json = JsonSerializer.Serialize(@class, options);
            Console.WriteLine(json);

        }
        publicclassSome
        {
            publicstring Message { get; set; }
            publicstring Data { get; set; }
        }
    }
}

Extended support for ignoring default values

When you serializing in .NET Core 3.x, there was only possible to ignore the null value for reference or nullable value-typed properties, the JsonSerilizerOptions.IgnoreNullValues setting was only applicable across an entire input object graph. We have to add support to ignore default values for non-nullable value types, such as int and float. Further, we are now possible to cherry-pick properties and fields to be ignored when default.

Example
 

var options = newJsonSerializerOptions
        {
             DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
        };

           varobj = newyourClass();
           stringjson = JsonSerializer.Serialize(obj, options);
           Console.WriteLine(json);

 publicclassyourClass
        {
           publicintyourInt{ get; set; }

            [JsonIgnore(Condition = JsonIgnoreCondition.Never)]
            publicboolyourBool{ get; set; }

            publicstringyourString{ get; set; }
        }

Here we can see that we have passed the default value JsonIgnoreCondition.WhenWritingDefault in the JsonSerializerOptions class and this class declared with options variable, the JsonIgnoreCondition.WhenWritingDefault is ignoring only null values, but not default values.

After, we put the class name yourClass is declared with a new keyword and it identify with theobj variable.

Then, the obj and options value pass in the JsonSerializer.Serialize method with defined by JSON variable, print the JSON variable with console.WriteLine .

Utility Constructors for JsonSerializerOptions

The JsonSerializerOptions coping the one instance to another instance,so we have added a copy constructor to JsonSerializerOptions which makes this easier for the user.

Example
 

JsonSerializerOptions opt = new()
            {
                Handling = JsonNumberHandling.AllowReadingFromString,
                ignoreCondition = JsonIgnoreCondition.WhenWritingNull,
                Converters = { newJsonStringEnumConverter() }
            };
JsonSerializerOptionsnewOpt = new(opt)
            {
                Handling = JsonNumberHandling.Strict
            };

           Console.WriteLine(newOpt.Handling);

           Console.WriteLine(newOpt.ignoreCondition);

           Console.WriteLine(newOpt.Converters[0]);		

There are some common set of options when processing JSON data in web contexts is to use the camelCase naming policy. You specify case-insensitive matching when deserializing, and allow reading quoted numbers. You have to declare the JsonSerializerDefaults.Webenum value, and a new constructor that takes a JsonSerializerDefaults value, provide an easy way to reuse these options in a consistent way across multiple layers of an application.

Example
 

JsonSerializerOptionsserializerOptions = new (JsonSerializerDefaults.Web);

Console.WriteLine(serializerOptions.PropertyNamingPolicy);

Console.WriteLine(serializerOptions.PropertyNameCaseInsensitive);   

Console.WriteLine(serializerOptions.Handling);

Looking to hire ASP.Net Development Company in USA ?

Your Search ends here.


Performance Improvements

There is a major difference between .NET Core 3.1 and .NET 5, and we have improved performance in the following areas.

  1. Performance improved for collections by serialization and deserialization
  2. Performance improved for small types by serialization and deserialization
  3. Performance improved for case-insensitive and missing-property cases by deserialization.
  4. And performance improved for long JSON strings by serialization.

These above improvements are going to be specifically meaningful for high-performance apps.

Improved Performance for Collections

The significant improvements for large collections made by us. These improvements are characterized in much more detail at dotnet/runtime #2259.

Improved Performance for Small Types

The significant efforts to improve .NET performance in the TechEmpower JSON benchmark in .NET 5.0. The performance when observing work done within the serializer is now ~19% better.

Performance improved for case-insensitive by deserialization

There are most common issues with using JSON is a mismatch of naming conventions with .NET design guidelines. The camelCase is used in JSON properties and the PascalCase is used in .NET properties and fields.

Performance improved for long JSON strings by serialization

When we write relatively large JSON strings using the writer directly, there is ~30% improvement.

Conclusion

In this blog, we have learned about the System.Text.Json in .NET 5.0, and which JSON is better for developers like among Newtonsoft.Json and System.Text.Json. Before introducing .NET Core 3.1, most of the developers were using Newtonsoft.Json. It doesn’t provide many features compare to System.Text.Json.