JSON & XML Serialization in C# Using System.Text.Json
Introduction
System.Text.Json is a high-performance, built-in JSON library in .NET Core 3.0 and later. Unlike the widely-used Newtonsoft.Json, System.Text.Json is optimized for speed, lower memory usage, and native integration within the .NET ecosystem.
This guide will walk you through how to serialize and deserialize objects with System.Text.Json
, format the output, manage nulls, and briefly compare it to XML serialization using System.Xml.Serialization
.
Namespaces and Installation
If you're using .NET Core 3.0+ or .NET 5/6/7, System.Text.Json
comes pre-installed. Just include the following namespace in your file:
using System.Text.Json;
For older projects, you can install the NuGet package:
dotnet add package System.Text.Json
Basic JSON Serialization
To serialize an object into JSON, use the JsonSerializer.Serialize()
method:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
var product = new Product { Id = 1, Name = "Laptop" };
string json = JsonSerializer.Serialize(product);
Console.WriteLine(json);
This produces: {"Id":1,"Name":"Laptop"}
. Clean, fast, and no extra dependencies.
JSON Deserialization
To convert a JSON string back into a C# object, use JsonSerializer.Deserialize()
:
string json = "{\"Id\":1,\"Name\":\"Laptop\"}";
Product deserialized = JsonSerializer.Deserialize<Product>(json);
Console.WriteLine(deserialized.Name); // Output: Laptop
Formatting JSON Output
By default, JSON output is compact. You can enable indented formatting using JsonSerializerOptions
to make it more readable:
var options = new JsonSerializerOptions
{
WriteIndented = true
};
string prettyJson = JsonSerializer.Serialize(product, options);
Console.WriteLine(prettyJson);
This outputs:
{ "Id": 1, "Name": "Laptop" }
Ignore Null Values
To exclude properties with null
values from the JSON output, set DefaultIgnoreCondition
to JsonIgnoreCondition.WhenWritingNull
:
var options = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = true
};
string json = JsonSerializer.Serialize(product, options);
To use JsonIgnoreCondition
, include:
using System.Text.Json.Serialization;
Custom Property Naming (Camel Case)
You can convert PascalCase to camelCase by setting a naming policy:
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
string jsonCamel = JsonSerializer.Serialize(product, options);
This helps when working with JavaScript clients or REST APIs expecting camelCase.
XML Serialization with System.Xml.Serialization
If you need to work with XML instead of JSON, you can use the XmlSerializer
class from the System.Xml.Serialization
namespace.
using System.Xml.Serialization;
using System.IO;
var product = new Product { Id = 1, Name = "Laptop" };
var serializer = new XmlSerializer(typeof(Product));
using (var writer = new StreamWriter("product.xml"))
{
serializer.Serialize(writer, product);
}
This writes the Product object into a structured XML format. XML is more verbose but can be useful for legacy systems and configuration scenarios.
JSON vs XML Serialization: Key Differences
Feature | System.Text.Json (JSON) | System.Xml.Serialization (XML) |
---|---|---|
Format | Lightweight, compact | Verbose, tag-based |
Performance | Faster | Slower |
Human-Readability | High | Moderate |
Schema Support | Limited | Supports XSD |
Use Case | Web APIs, front-end apps | Legacy systems, config files |
Best Practices
- Use
System.Text.Json
for modern .NET apps needing performance and minimal dependencies. - Always use
try-catch
when deserializing user input to handle malformed data safely. - Use
JsonSerializerOptions
to customize behavior like ignoring nulls or formatting output. - For XML, explicitly define your class structure and consider using
[XmlElement]
or[XmlAttribute]
for fine control. - When performance is critical, prefer JSON over XML due to smaller payload and faster processing.
Conclusion
Serialization is fundamental in modern application development—whether you're persisting data, sending it over the wire, or transforming objects. With System.Text.Json, you get a powerful, built-in way to work with JSON that's fast, reliable, and highly configurable. For XML needs, .NET’s System.Xml.Serialization still provides robust support for complex, schema-bound structures.
Knowing when and how to use both empowers you to build flexible, scalable systems that can integrate with modern APIs and legacy services alike.
FAQs
1. Can System.Text.Json serialize private properties?
No. Only public properties are serialized by default. Use custom converters if needed.
2. Is System.Text.Json faster than Newtonsoft.Json?
Yes. It generally performs better, especially in .NET Core and later, but lacks some advanced features.
3. Can I serialize complex types with circular references?
By default, no. You need to configure reference handling in JsonSerializerOptions
.
4. Does XmlSerializer support attributes and namespaces?
Yes. It supports attributes like [XmlElement]
, [XmlAttribute]
, and namespace declarations.
5. Which should I use for REST APIs?
JSON is the standard for RESTful APIs. Use System.Text.Json
or Newtonsoft.Json
depending on your project’s needs.
Post a Comment