Camelcase Serialization in .Net 9

In .NET 9, developers have been granted a powerful tool to enhance data serialization: CamelCase Serialization. This feature facilitates smoother interoperability with systems and frameworks that expect camelCase formatted data.

Using CamelCase Serialization with JsonSerializerOptions

To enable CamelCase Serialization, we'll utilize the JsonSerializerOptions class, which provides fine-grained control over serialization settings. Specifically, we'll set the PropertyNamingPolicy property to CamelCaseNamingPolicy, instructing the serializer to use camelCase for property names.

Here's how you can do it.

using System;
using System.Text.Json;

class Program
{
    static void Main(string[] args)
    {
       
        var person = new Person
        {
            FirstName = "Mahesh",
            LastName = "Chand",
            Age = 40
        };

        // Configure JsonSerializerOptions for CamelCase Serialization
        var options = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };

        // Serialize the object to JSON with CamelCase property names
        string json = JsonSerializer.Serialize(person, options);
        Console.WriteLine(json);
    }
}

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

In this example

  1. We define a simple Person class with properties for FirstName, LastName, and Age.
  2. Inside the Main method, we create an instance of the Person class.
  3. We configure a new instance of JsonSerializerOptions and set its PropertyNamingPolicy property to JsonNamingPolicy.CamelCase.
  4. Using JsonSerializer.Serialize method, we serialize the Person object to JSON, applying CamelCase Serialization based on the configured options.
  5. Finally, we print the serialized JSON string to the console.

Example Output

{"firstName":"Mahesh","lastName":"Chand","age":40}

As demonstrated, the property names in the resulting JSON string are in camelCase format, as dictated by the JsonSerializerOptions configuration.

Conclusion

Utilizing CamelCase Serialization with JsonSerializerOptions in .NET 9 is a straightforward process that empowers developers to seamlessly integrate their applications with systems and frameworks expecting camelCase formatted data. By employing this approach, developers can enhance interoperability, promote code consistency, and streamline data exchange in their .NET applications.

😊Please consider liking and following me for more articles and if you find this content helpful.👍


Similar Articles
Citiustech Healthcare Technology Pvt Ltd
CitiusTech plays a deep and meaningful role in powering the future of healthcare.