C# Programming
JSON String
.NET Framework
Object Serialization
Programming Tips

How do I turn a C# object into a JSON string in .NET?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Turning a C# object into a JSON string is serialization: you take an in-memory object graph and convert it into text that can be logged, sent over HTTP, or written to a file. In modern .NET, the normal built-in tool is System.Text.Json, although Newtonsoft.Json is still common in older codebases and some advanced scenarios.

Serialize With System.Text.Json

For new .NET code, the direct answer is JsonSerializer.Serialize.

csharp
1using System;
2using System.Text.Json;
3
4public class Product
5{
6    public int Id { get; set; }
7    public string Name { get; set; } = string.Empty;
8    public decimal Price { get; set; }
9}
10
11public class Program
12{
13    public static void Main()
14    {
15        var product = new Product
16        {
17            Id = 1,
18            Name = "Apple",
19            Price = 0.75m
20        };
21
22        string json = JsonSerializer.Serialize(product);
23        Console.WriteLine(json);
24    }
25}

That produces a compact JSON string. For many API and logging scenarios, this is enough.

Control The Output With Serializer Options

Real applications often need more than the compact default. JsonSerializerOptions lets you control indentation, property naming, and null handling.

csharp
1using System;
2using System.Text.Json;
3using System.Text.Json.Serialization;
4
5var product = new Product
6{
7    Id = 1,
8    Name = "Apple",
9    Price = 0.75m
10};
11
12var options = new JsonSerializerOptions
13{
14    WriteIndented = true,
15    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
16    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
17};
18
19string json = JsonSerializer.Serialize(product, options);
20Console.WriteLine(json);

This is the usual place to make JSON output match the conventions of an HTTP API or frontend client.

Collections And Nested Objects Work Naturally

Serialization is not limited to one flat object. Lists and nested objects are handled automatically as long as the contained types are serializable.

csharp
1using System;
2using System.Collections.Generic;
3using System.Text.Json;
4
5public class Order
6{
7    public int OrderId { get; set; }
8    public List<Product> Products { get; set; } = new();
9}
10
11var order = new Order
12{
13    OrderId = 1001,
14    Products = new List<Product>
15    {
16        new Product { Id = 1, Name = "Apple", Price = 0.75m },
17        new Product { Id = 2, Name = "Banana", Price = 1.25m }
18    }
19};
20
21string json = JsonSerializer.Serialize(order, new JsonSerializerOptions
22{
23    WriteIndented = true
24});
25
26Console.WriteLine(json);

This is one reason JSON serialization is so useful for APIs: your object structure maps naturally into JSON objects and arrays.

When Newtonsoft.Json Is Still Useful

Older .NET applications often use Json.NET, and some teams still prefer it for compatibility or specialized features. The equivalent basic call is:

csharp
1using Newtonsoft.Json;
2
3string json = JsonConvert.SerializeObject(product);
4Console.WriteLine(json);

Indented output looks like this:

csharp
1var settings = new JsonSerializerSettings
2{
3    Formatting = Formatting.Indented,
4    NullValueHandling = NullValueHandling.Ignore
5};
6
7string json = JsonConvert.SerializeObject(product, settings);

If you are working in an existing codebase that already uses Json.NET pervasively, consistency may matter more than switching every serializer call immediately.

Think About Serialization Boundaries

The basic API call is easy, but the real engineering question is which object you should serialize. Dumping a full ORM entity or a complicated domain object graph directly into JSON can expose fields you did not intend to publish.

In public APIs, it is often better to serialize a DTO designed for the response contract rather than whatever entity type happens to be available. The JSON string should reflect the data contract, not accidental internal structure.

Common Pitfalls

  • Serializing the wrong object type and exposing fields that should stay internal.
  • Expecting JSON property names to use camelCase without configuring the serializer.
  • Forgetting that cycles and unsupported members can cause serialization failures.
  • Mixing System.Text.Json and Newtonsoft.Json conventions in the same API without noticing behavioral differences.
  • Treating serialization as a formatting concern only, when it is really part of the application's external contract.

Summary

  • In modern .NET, use JsonSerializer.Serialize from System.Text.Json to turn a C# object into JSON text.
  • Add JsonSerializerOptions when you need indentation, camelCase names, or null-handling rules.
  • Nested objects and collections serialize naturally when the types are supported.
  • 'Newtonsoft.Json remains valid in older or feature-rich codebases, but the core idea is the same: serialize the right object deliberately.'

Course illustration
Course illustration

All Rights Reserved.