dcsimg
October 15, 2019
Hot Topics:

Introducing the New System.Text.Json APIs

  • August 8, 2019
  • By Hannes DuPreez
  • Send Email »
  • More Articles »

.NET Core 3.0 ships with a new namespace called System.Text.Json. It includes support for a reader and writer, a serializer, and a document object model (DOM). JSON has become crucial to all modern .NET applications. .NET, unfortunately, hasn't had a decent way to deal with built-in JSON, causing .NET to rely on Json.NET. With the release of .NET Core 3, which includes the new JSON APIs, this has changed.

The main reasons for (finally) building a new JSON library are threefold:

  • The need for high performance
  • The need to replace JSON.NET dependency from the ASP.NET Core
  • The need to provide an ASP.NET Core integration package for JSON.NET

Installing System.Text.Json

Use these steps to install the System.Text.Json APis:

  1. Start a new project or open an existing project where this could be useful.
  2. Navigate to the Project menu.
  3. Select Manage NuGet Packages.
  4. Select Browse.
  5. Type System.Text.Json, as shown in Figure 1:

    System.Text.Json NuGet package
    Figure 1: System.Text.Json NuGet package

  6. Click Install.

The package is now installed into your project.

Equally important before you start chipping away at your code, you need to keep in mind that you might need to import either one or both of these namespaces:

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

Serialization

The System.Text.Json serializer reads and writes JSON asynchronously. Here is a small example of Serializing:

class Student
{
   public int StudentID { get; set; }
   public string StudentNames { get; set; }
   public string StudentCourseCode { get; set; }
}
string Serialize(Student value)
{
   return JsonSerializer.ToString<Student>(value);
}

Deserialization

The result of the following Deserializing code could be something like:

"StudentID": 123,
"StudentNames": "Hannes du Preez",
"StudentCourseCode": "P101",
Student Deserialize(string json)
{
   var options = new JsonSerializerOptions
   {
      AllowTrailingCommas = true
   };

   return JsonSerializer.Parse<Student>(json, options);
}

Writer

Have a look at the next example:

var options = new JsonWriterOptions
{
   Indented = true
};
using (var stream = new MemoryStream())
{
   using (var writer = new Utf8JsonWriter(stream, options))
   {
      writer.WriteStartObject();
      writer.WriteNumber("StudentID", 123);
      writer.WriteString("StudentNames", "Hannes du Preez");
      writer.WriteString("StudentCourseCode", "P101");
      writer.WriteEndObject();
   }
   string json = Encoding.UTF8.GetString(stream.ToArray());
   Console.WriteLine(json);
}

The preceding code simply writes the data supplied into a new memory stream object. It starts by indicating WriteStartObject and ends with WriteEndObject.

Reader

Using the Reader is a bit trickier; you need to test for the types of data that is received, by using the TokenType. Here is a very quick example:

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;
      }
   }
   Console.WriteLine();
}

Conclusion

The inclusion of System.Text.Json is a huge step forward for Microsoft and .NET Core. In this very brief article, we just quickly had a look into it. Perhaps at a later stage, I can include other examples.







Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.


Thanks for your registration, follow us on our social networks to keep up-to-date