How to Serialize to JSON in C# Quickly and Easily
In C#, you can serialize an object to JSON using
System.Text.Json.JsonSerializer.Serialize(). This method converts your object into a JSON string that you can save or send over a network.Syntax
The basic syntax to serialize an object to JSON in C# is:
string jsonString = JsonSerializer.Serialize(objectToSerialize);Here, objectToSerialize is the object you want to convert to JSON, and jsonString will hold the resulting JSON text.
You need to include using System.Text.Json; at the top of your file.
csharp
using System.Text.Json;
// Serialize an object to JSON string
string jsonString = JsonSerializer.Serialize(objectToSerialize);Example
This example shows how to serialize a simple Person object to a JSON string and print it.
csharp
using System; using System.Text.Json; public class Person { public string Name { get; set; } public int Age { get; set; } } public class Program { public static void Main() { Person person = new Person { Name = "Alice", Age = 30 }; string jsonString = JsonSerializer.Serialize(person); Console.WriteLine(jsonString); } }
Output
{"Name":"Alice","Age":30}
Common Pitfalls
- For serialization to work, the object must have public properties or fields.
- Trying to serialize private fields or methods will not include them in JSON.
- Not including
using System.Text.Json;causes errors. - Older code may use
Newtonsoft.Json(Json.NET), butSystem.Text.Jsonis now preferred.
csharp
/* Wrong: private fields won't serialize */ public class WrongPerson { private string Name = "Bob"; private int Age = 25; } /* Right: use public properties */ public class RightPerson { public string Name { get; set; } = "Bob"; public int Age { get; set; } = 25; }
Quick Reference
Here is a quick summary of key points for JSON serialization in C#:
| Action | Code Snippet |
|---|---|
| Serialize object to JSON string | JsonSerializer.Serialize(object) |
| Deserialize JSON string to object | JsonSerializer.Deserialize |
| Include namespace | using System.Text.Json; |
| Serialize with options | JsonSerializer.Serialize(object, new JsonSerializerOptions { WriteIndented = true }) |
Key Takeaways
Use System.Text.Json.JsonSerializer.Serialize() to convert objects to JSON strings.
Objects must have public properties to be serialized correctly.
Include 'using System.Text.Json;' to access serialization methods.
System.Text.Json is the modern, built-in way to handle JSON in C#.
Avoid serializing private fields; use public properties instead.