System.Text.Json

System.Text.Json is the recommended way to serialize and deserialize JSON data in .NET applications. It is a high-performance, low-memory JSON library that is built into the .NET runtime.

Serialization

Serialization is the process of converting an object to a JSON string. To serialize an object, you can use the JsonSerializer.Serialize method.

// Sample class to be serialized
          public class Person
          {
              public string FirstName { get; set; }
              public string LastName { get; set; }
              public int Age { get; set; }
          }
          
          // Serialize the object to JSON string
          var person = new Person { FirstName = "John", LastName = "Doe", Age = 30 };
          string jsonString = JsonSerializer.Serialize(person);
          
          // Print the JSON string to the console
          Console.WriteLine(jsonString);
          

This will output the following JSON string:

{"FirstName":"John","LastName":"Doe","Age":30}
          

Deserialization

Deserialization is the process of converting a JSON string to an object. To deserialize a JSON string, you can use the JsonSerializer.Deserialize method.

// Deserialize the JSON string to a Person object
          Person person = JsonSerializer.Deserialize<Person>(jsonString);
          
          // Print the values of the Person object to the console
          Console.WriteLine($"Name: {person.FirstName} {person.LastName}");
          Console.WriteLine($"Age: {person.Age}");
          

This will output the following to the console:

Name: John Doe
          Age: 30
          

Custom Serialization

You can customize the serialization process by using the JsonSerializerOptions class. This class allows you to configure how the serializer should handle properties, types, and other aspects of the serialization process.

Property Naming:

You can specify a different naming convention for properties in the JSON output using the PropertyNamingPolicy property.

// Use camelCase naming convention
          JsonSerializerOptions options = new JsonSerializerOptions
          {
              PropertyNamingPolicy = JsonNamingPolicy.CamelCase
          };
          
          string jsonString = JsonSerializer.Serialize(person, options);
          
          // Output: {"firstName":"John","lastName":"Doe","age":30}
          

Ignoring Properties:

You can exclude certain properties from serialization using the JsonIgnore attribute.

public class Person
          {
              public string FirstName { get; set; }
              public string LastName { get; set; }
          
              [JsonIgnore]
              public int Age { get; set; }
          }
          
          // Serialize the object to JSON string
          string jsonString = JsonSerializer.Serialize(person);
          
          // Output: {"FirstName":"John","LastName":"Doe"}
          

Custom Converters:

You can create custom converters to serialize and deserialize objects in a specific way. For example, you could create a custom converter to handle dates or enums.

// Custom converter for DateOnly type
          public class DateOnlyConverter : JsonConverter<DateOnly>
          {
              public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
              {
                  return DateOnly.FromDateTime(DateTime.Parse(reader.GetString()));
              }
          
              public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
              {
                  writer.WriteStringValue(value.ToString("yyyy-MM-dd"));
              }
          }
          
          // Register the custom converter with the JsonSerializerOptions
          JsonSerializerOptions options = new JsonSerializerOptions();
          options.Converters.Add(new DateOnlyConverter());
          
          // Serialize the object with the custom converter
          string jsonString = JsonSerializer.Serialize(person, options);
          
          // Output: {"BirthDate":"2023-09-20"}
          

Benefits of System.Text.Json

  • High Performance: System.Text.Json is highly optimized for performance and uses low memory.
  • Built-in Support: It is built into the .NET runtime and does not require any external dependencies.
  • Customizable: It provides a wide range of options for customizing the serialization process.
  • Ease of Use: It is easy to use with a simple and consistent API.

Limitations of System.Text.Json

  • No Support for Non-Standard JSON: System.Text.Json does not support non-standard JSON formats, such as JSON with comments or trailing commas.
  • Limited Support for Custom Serialization: While System.Text.Json provides options for custom serialization, it may not be suitable for all complex serialization scenarios.

References