Enhanced feature of new System.Text.Json APIs in ASP.NET


Isn't it fun,

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

 
 

RunAnalyzer

An earlier version of ASP.NET MVC and ASP.NET Core use JSON library for JSON Processing. ASP.NET Core 3 provides built-in support for JSON serialization and deserialization so that the application did not depend on the JSON library. ASP.NET 5 provides built-in support for a brand new namespace System.Text.Json for reading/writing, a DOM (Document Object Model), and a Serialize.

Table of Content

Get the JSON library

  1. Asp.Net 5 https://dotnet.microsoft.com/download/dotnet/5.0 provide in-built System.Text.Json library.
  2. .NET Core 3.x or .NET Framework Application requires to install JSON library from https://www.nuget.org/packages/System.Text.Json/
  3. ASP.NET Core 2.2 to 3.0 or 5.0, use System.Text.Json default serialization library.

What is System.Text.Json?

System.Text.Json is a built-in JSON (JavaScript Object Notation) library used in ASP.NET for converting object type to JSON string and vice versa and it provides support for UTF-8 text encoding. Asp.Net 3.0 provide JsonSerializer JSON library for First time, for processing JSON data.

The Future of JSON

For .NET Application, JSON data processing has become an essential part.

The main reasons for building a new JSON library are:

Provide High-Performance JSON APIs

A new set of JSON APIs require performance using Span and this JSON API can process UTF-8 without transcoding to UTF-16. When throughput is a key requirement in ASP.NET Core both concepts are critical. With System.Text.Json, we can achieve 1.3x-5x speed up based on the scenario.


Remove JSON dependency from ASP.NET Core

ASP.NET Core application depends on JSON.NET and this provides tight integration between ASP.Net core and Json.Net. However, Json.Net is updated so that the developer has to use a specific version. Remove JSON dependency from ASP.Net Core so that user can choose which version to use, without fear of accidental break the underlying platform.


Provide ASP.NET Core Integration package for JSON.NET

Json.Net provides many facilities and an option to handle JSON. The developer can install Json.Net integration for Asp.Net Core as a NuGet package. So that developer can get all options and facilities from Json.Net. This work item is to ensure the user has the right extension point so that other parties can provide a similar integration package for the JSON library.

Asp.Net provide the following types in the Sytem.Text.Json namespace:

  1. JsonSerializer: It is used to serialize .Net objects to JSON format and deserialize JSON into .NET objects.
  2. JsonDocument: It is used to provide random access capabilities for examining the structural content of a JSON value without instating data values. JSON document is immutable.
  3. JsonElement: It is use to represents a specific JSON value within a JsonDocument.
  4. Utf8JsonWriter: Using Utf8JsonWriter high-performance API, developer can write forward-only, non-cached UTF-8 encoded JSON text.
  5. Utf8JsonReader: It is used to provide a high-performance API for forward-only, token-by-token processing of UTF-8 encoded JSON text.
   

ow to install System.Text.Json?

Use the following steps to install the Sytem.Text.Json APIs:

Step 1: Create a new project or open an existing project where System.Text.Json could be used.

Step 2: Go to the Project menu.

Step 3: Open the Manage NuGet package.

Step 4: Open Browse.

Step 5: Search System.Text.Json as shown below:

RunAnalyzer

Figure: System.Text.Json NuGet package.

Step 6: Click Install.

The System.Text.Json is now included in your application.

Using System.Text.Json directly

For example, you have to import the following two namespaces:

Example:

using System.Text.Jaso;
using System.Text.Jason.Serialization; 

Serialization

For reading and writing JSON asynchronously system.Text.Json serialize is used .The system.Text.Json JSON library is optimized for UTF-8 text, for REST API, and back-end application.

Following is a small example of Serializing:
 

class Employee
{
   public int Emp_Code { get; set; }
   public string Emp_FullName { get; set; }
   public string Emp_EmailAddress{ get; set; }
}
string Serialize(Employee value)
{
   return JsonSerializer.ToString< Employee >(value);
}

By default, it produces a minified JSON. JsonSerializerOptions is used to produce human-readable by passing an instance of JsonSerializerOptions to the serializer.

JsonSerializerOptions is used to configure another setting like handling of comments, trailing comma, and naming policies.
 

string SerializePrettyPrint(Employee value)
{
    var options = new JsonSerializerOption    {
        WriteIndented = true
    };
 return JsonSerializer.ToString< Employee >(value, options);
}

Deserialization

Deserialization work similarly and the result of the below code could be something like:
 

Employee Deserialize(string json)
{
    var options = new JsonSerializerOptions{
        AllowTrailingCommas = true
    };
    return JsonSerializer.Parse(json, options);
}
{
    "Emp_Code": 1,
   "Emp_FullName": "Virat Kohli",
     "Emp_EmailAddress: "chiku@gmail.com",
 }

System.Text.Json API also supports asynchronous serialization and deserialization:
 

async Task SerializeAsync(Employee value, Stream stream)
{
    await JsonSerializer.WriteAsync(value, stream);
}
 

Looking for the Best ASP.Net Web Development Company ?

Your Search ends here.

 

The custom attribute can be used to control serialization behavior like ignoring property, specify the name of the property in JSON.

Example:
 

class Employee
{
    public int Emp_Code { get ; set ; }
    public string Emp_FullName { get ; set ; }
    public date Emp_Birthdate { get ; set ;  }
    [JsonPropertyName("dept")]
    public string Emp_EmailAddress { get ; set ; }

    //Don't serialize this property.
    [JsonIgnore]
    public bool IsEmp_Active { get ; set ;}
}

Writer

Below code writes data into a new memory stream object and it starts with WriteStartObject and ends with WriteEndObject. The writer is straight forward to use.

The Following code is used to write data:
 

var attribute = new JsonWriterOptions{
   Indented = true
};
using (var data= new MemoryStream()) {
   using (var record = new Utf8JsonWriter(data, attribute))  {
      record.WriteStartObject();
      record.WriteNumber("Emp_Code", 1);
      record.WriteString("Emp_FullName", "Virat kohli");
      record.WriteString("Emp_Designation", "Admin");
      record.WriteEndObject();
   }
   string json = Encoding.UTF8.GetString(stream.ToArray());
   Console.WriteLine(json);
}

Reader

The reader use token type to test for the received data and it is a bit trickier.

Following is an example of reader:
 

byte[] data = Encoding.UTF8.GetBytes(json);
Utf8JsonReader reader = new Utf8JsonReader(data,
   isFinalBlock: true, state: default);
while (reader.Read())
{
   Console.Write(reader.TokenType);
   switch (reader.TokenType)
   {
      case JsonTokenType.PropertyName:
      case JsonTokenType.String:
      {
         string text = reader.GetString();
         Console.Write(" ");
         Console.Write(text);
         break;
      }
      case JsonTokenType.Number:
      {
         int value = reader.GetInt32();
         Console.Write(" ");
         Console.Write(value);
         break;
      }
//Other token types 
   }
   Console.WriteLine();
}

Integration with ASP.NET Core MVC

Asp.Net Core provides support for reading and writing JSON.System.Json.Text JSON library is used for serializing and deserializing JSON.

Serializing can be configured using following Code in ConfigureServices method -> startup.cs file
 

services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);

Conclusion

In this blog, we have discussed the New System.Text.Json APIs and also discussed the reason for the new JSON library, serialization, deserialization, and reader/writer with example. Asp.Net core provide in-built support for JSON for reading/write, and serialization/deserialization.

Enhanced feature of new System.Text.Json APIs in ASP.NET

RunAnalyzer

An earlier version of ASP.NET MVC and ASP.NET Core use JSON library for JSON Processing. ASP.NET Core 3 provides built-in support for JSON serialization and deserialization so that the application did not depend on the JSON library. ASP.NET 5 provides built-in support for a brand new namespace System.Text.Json for reading/writing, a DOM (Document Object Model), and a Serialize.

Table of Content

Get the JSON library

  1. Asp.Net 5 https://dotnet.microsoft.com/download/dotnet/5.0 provide in-built System.Text.Json library.
  2. .NET Core 3.x or .NET Framework Application requires to install JSON library from https://www.nuget.org/packages/System.Text.Json/
  3. ASP.NET Core 2.2 to 3.0 or 5.0, use System.Text.Json default serialization library.

What is System.Text.Json?

System.Text.Json is a built-in JSON (JavaScript Object Notation) library used in ASP.NET for converting object type to JSON string and vice versa and it provides support for UTF-8 text encoding. Asp.Net 3.0 provide JsonSerializer JSON library for First time, for processing JSON data.

The Future of JSON

For .NET Application, JSON data processing has become an essential part.

The main reasons for building a new JSON library are:

Provide High-Performance JSON APIs

A new set of JSON APIs require performance using Span and this JSON API can process UTF-8 without transcoding to UTF-16. When throughput is a key requirement in ASP.NET Core both concepts are critical. With System.Text.Json, we can achieve 1.3x-5x speed up based on the scenario.


Remove JSON dependency from ASP.NET Core

ASP.NET Core application depends on JSON.NET and this provides tight integration between ASP.Net core and Json.Net. However, Json.Net is updated so that the developer has to use a specific version. Remove JSON dependency from ASP.Net Core so that user can choose which version to use, without fear of accidental break the underlying platform.


Provide ASP.NET Core Integration package for JSON.NET

Json.Net provides many facilities and an option to handle JSON. The developer can install Json.Net integration for Asp.Net Core as a NuGet package. So that developer can get all options and facilities from Json.Net. This work item is to ensure the user has the right extension point so that other parties can provide a similar integration package for the JSON library.

Asp.Net provide the following types in the Sytem.Text.Json namespace:

  1. JsonSerializer: It is used to serialize .Net objects to JSON format and deserialize JSON into .NET objects.
  2. JsonDocument: It is used to provide random access capabilities for examining the structural content of a JSON value without instating data values. JSON document is immutable.
  3. JsonElement: It is use to represents a specific JSON value within a JsonDocument.
  4. Utf8JsonWriter: Using Utf8JsonWriter high-performance API, developer can write forward-only, non-cached UTF-8 encoded JSON text.
  5. Utf8JsonReader: It is used to provide a high-performance API for forward-only, token-by-token processing of UTF-8 encoded JSON text.
   

ow to install System.Text.Json?

Use the following steps to install the Sytem.Text.Json APIs:

Step 1: Create a new project or open an existing project where System.Text.Json could be used.

Step 2: Go to the Project menu.

Step 3: Open the Manage NuGet package.

Step 4: Open Browse.

Step 5: Search System.Text.Json as shown below:

RunAnalyzer

Figure: System.Text.Json NuGet package.

Step 6: Click Install.

The System.Text.Json is now included in your application.

Using System.Text.Json directly

For example, you have to import the following two namespaces:

Example:

using System.Text.Jaso;
using System.Text.Jason.Serialization; 

Serialization

For reading and writing JSON asynchronously system.Text.Json serialize is used .The system.Text.Json JSON library is optimized for UTF-8 text, for REST API, and back-end application.

Following is a small example of Serializing:
 

class Employee
{
   public int Emp_Code { get; set; }
   public string Emp_FullName { get; set; }
   public string Emp_EmailAddress{ get; set; }
}
string Serialize(Employee value)
{
   return JsonSerializer.ToString< Employee >(value);
}

By default, it produces a minified JSON. JsonSerializerOptions is used to produce human-readable by passing an instance of JsonSerializerOptions to the serializer.

JsonSerializerOptions is used to configure another setting like handling of comments, trailing comma, and naming policies.
 

string SerializePrettyPrint(Employee value)
{
    var options = new JsonSerializerOption    {
        WriteIndented = true
    };
 return JsonSerializer.ToString< Employee >(value, options);
}

Deserialization

Deserialization work similarly and the result of the below code could be something like:
 

Employee Deserialize(string json)
{
    var options = new JsonSerializerOptions{
        AllowTrailingCommas = true
    };
    return JsonSerializer.Parse(json, options);
}
{
    "Emp_Code": 1,
   "Emp_FullName": "Virat Kohli",
     "Emp_EmailAddress: "chiku@gmail.com",
 }

System.Text.Json API also supports asynchronous serialization and deserialization:
 

async Task SerializeAsync(Employee value, Stream stream)
{
    await JsonSerializer.WriteAsync(value, stream);
}
 

Looking for the Best ASP.Net Web Development Company ?

Your Search ends here.

 

The custom attribute can be used to control serialization behavior like ignoring property, specify the name of the property in JSON.

Example:
 

class Employee
{
    public int Emp_Code { get ; set ; }
    public string Emp_FullName { get ; set ; }
    public date Emp_Birthdate { get ; set ;  }
    [JsonPropertyName("dept")]
    public string Emp_EmailAddress { get ; set ; }

    //Don't serialize this property.
    [JsonIgnore]
    public bool IsEmp_Active { get ; set ;}
}

Writer

Below code writes data into a new memory stream object and it starts with WriteStartObject and ends with WriteEndObject. The writer is straight forward to use.

The Following code is used to write data:
 

var attribute = new JsonWriterOptions{
   Indented = true
};
using (var data= new MemoryStream()) {
   using (var record = new Utf8JsonWriter(data, attribute))  {
      record.WriteStartObject();
      record.WriteNumber("Emp_Code", 1);
      record.WriteString("Emp_FullName", "Virat kohli");
      record.WriteString("Emp_Designation", "Admin");
      record.WriteEndObject();
   }
   string json = Encoding.UTF8.GetString(stream.ToArray());
   Console.WriteLine(json);
}

Reader

The reader use token type to test for the received data and it is a bit trickier.

Following is an example of reader:
 

byte[] data = Encoding.UTF8.GetBytes(json);
Utf8JsonReader reader = new Utf8JsonReader(data,
   isFinalBlock: true, state: default);
while (reader.Read())
{
   Console.Write(reader.TokenType);
   switch (reader.TokenType)
   {
      case JsonTokenType.PropertyName:
      case JsonTokenType.String:
      {
         string text = reader.GetString();
         Console.Write(" ");
         Console.Write(text);
         break;
      }
      case JsonTokenType.Number:
      {
         int value = reader.GetInt32();
         Console.Write(" ");
         Console.Write(value);
         break;
      }
//Other token types 
   }
   Console.WriteLine();
}

Integration with ASP.NET Core MVC

Asp.Net Core provides support for reading and writing JSON.System.Json.Text JSON library is used for serializing and deserializing JSON.

Serializing can be configured using following Code in ConfigureServices method -> startup.cs file
 

services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);

Conclusion

In this blog, we have discussed the New System.Text.Json APIs and also discussed the reason for the new JSON library, serialization, deserialization, and reader/writer with example. Asp.Net core provide in-built support for JSON for reading/write, and serialization/deserialization.