JSON

.NET JSON Serialization

Serializing JSON

.NET JSON serialization uses JsonSerializer.Serialize with types.

Introduction to JSON Serialization in .NET

JSON serialization in .NET is a powerful feature that allows developers to convert .NET objects into JSON format. This process is essential for data interchange between different systems and platforms. In .NET, the JsonSerializer.Serialize method from the System.Text.Json namespace is commonly used for serialization tasks.

Basic JSON Serialization Example

Let's start with a simple example of serializing a .NET object to a JSON string. Consider the following Person class:

To serialize an instance of the Person class, use the JsonSerializer.Serialize method:

This code will output a JSON string representation of the Person object:

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

Customizing JSON Serialization

The JsonSerializerOptions class allows you to customize the serialization process. For example, you can control properties like indentation, property naming policies, and more. Here's how to serialize with indented JSON:

This will output the JSON string with indentation for better readability:

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

Handling Complex Objects

JSON serialization in .NET can handle complex objects as well. If your object contains nested objects or collections, JsonSerializer.Serialize will process them recursively. For example, consider adding an Address class to the previous example:

With the new Address property in place, here's how you can serialize the Person object:

This will serialize the entire object graph, including the nested Address object:

{
  "FirstName": "John",
  "LastName": "Doe",
  "Age": 30,
  "Address": {
    "Street": "123 Main St",
    "City": "Anytown",
    "ZipCode": "12345"
  }
}