JSON & XML Serialization in C# Using Newtonsoft.Json
Introduction
Serialization is the process of converting an object into a format that can be easily stored or transferred. In C#, two of the most commonly used formats are JSON (JavaScript Object Notation) and XML (eXtensible Markup Language). While XML is still used in some legacy systems, JSON has become the de facto standard for data exchange, especially in web and API development.
This guide focuses on using Newtonsoft.Json (Json.NET), the most popular library for working with JSON in C#. You'll learn how to serialize and deserialize objects, handle formatting, ignore nulls, manage complex types, and compare it briefly with XML serialization using native .NET features.
Installing Newtonsoft.Json
First, you need to install the Newtonsoft.Json NuGet package:
// Using NuGet Package Manager Console
Install-Package Newtonsoft.Json
Or, use the .NET CLI:
dotnet add package Newtonsoft.Json
JSON Serialization with JsonConvert.SerializeObject()
To convert a C# object to a JSON string, use JsonConvert.SerializeObject()
. Here's a basic example:
using Newtonsoft.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
var person = new Person { Name = "Alice", Age = 30 };
string json = JsonConvert.SerializeObject(person);
Console.WriteLine(json);
This outputs: {"Name":"Alice","Age":30}
. The object is now a JSON-formatted string you can write to a file, send over a network, or store in a database.
JSON Deserialization with JsonConvert.DeserializeObject()
Deserialization is the reverse of serialization—it converts a JSON string back into a C# object. Use JsonConvert.DeserializeObject()
to easily convert JSON back to your defined class structure.
string json = "{\"Name\":\"Alice\",\"Age\":30}";
Person person = JsonConvert.DeserializeObject<Person>(json);
Console.WriteLine(person.Name); // Output: Alice
Console.WriteLine(person.Age); // Output: 30
Make sure the JSON structure matches your class definition to avoid nulls or runtime errors.
Formatting JSON Output
You can make the JSON output more readable by enabling formatting. Pass Formatting.Indented
as a parameter:
string prettyJson = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine(prettyJson);
This makes the output easier to read, especially for logs or config files:
{ "Name": "Alice", "Age": 30 }
Ignoring Null Values During Serialization
You can ignore properties with null
values by customizing JsonSerializerSettings
:
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
string jsonNoNulls = JsonConvert.SerializeObject(person, settings);
This prevents null fields from appearing in your JSON string, which is useful when working with APIs that reject nulls or when reducing payload size.
XML Serialization in C# (System.Xml.Serialization)
While JSON is more widely used in modern applications, XML is still required in some environments—especially older APIs and configuration systems. XML serialization is handled using the XmlSerializer
class from the System.Xml.Serialization
namespace.
using System.Xml.Serialization;
using System.IO;
Person person = new Person { Name = "Bob", Age = 25 };
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (TextWriter writer = new StreamWriter("person.xml"))
{
serializer.Serialize(writer, person);
}
This code writes a structured XML file representing the Person object. Unlike JSON, XML supports attributes, schemas, and namespaces, making it more verbose but also more structured.
For deserialization from XML:
using (TextReader reader = new StreamReader("person.xml"))
{
Person p = (Person)serializer.Deserialize(reader);
Console.WriteLine(p.Name); // Output: Bob
}
JSON vs XML Serialization: A Quick Comparison
Feature | JSON (Newtonsoft.Json) | XML (XmlSerializer) |
---|---|---|
Readability | Compact and human-readable | Verbose and structured |
Speed | Generally faster | Slightly slower |
Data Size | Smaller payloads | Larger due to tags |
Schema Support | Less formal | Supports XSD schemas |
Use Cases | Web APIs, modern apps | Legacy systems, SOAP |
Best Practices
- Use JSON for modern web and API projects.
- Prefer XML when integrating with legacy systems or .NET configuration files.
- Always validate your model structure before deserialization to avoid runtime issues.
- Use settings like
NullValueHandling
,Formatting
, andContractResolver
for clean JSON outputs. - Secure your deserialization logic to prevent JSON/XML injection attacks.
Conclusion
Serialization is a critical skill in C#, and Newtonsoft.Json makes working with JSON incredibly smooth and flexible. Whether you're building APIs, consuming web services, or saving state to files, JSON offers fast, compact, and readable solutions.
Meanwhile, XML serialization still plays an important role in .NET, especially in older apps or where structured validation and metadata are needed. Knowing both gives you the versatility to work across different systems and project types.
Mastering both serialization methods helps you write maintainable, scalable, and interoperable .NET code in real-world applications.
FAQs
1. Can I use Newtonsoft.Json in .NET Core and .NET 6/7?
Yes. Newtonsoft.Json is compatible with all modern .NET versions and is still widely used.
2. What’s the difference between Newtonsoft.Json and System.Text.Json?
System.Text.Json is the built-in serializer in .NET Core 3.0+. It's faster but less feature-rich than Newtonsoft.Json.
3. Can I serialize private properties using Json.NET?
Yes, with settings like DefaultContractResolver
and BindingFlags
.
4. How do I ignore a property during serialization?
Use the [JsonIgnore]
attribute from Newtonsoft.Json.
5. Can I mix JSON and XML in one app?
Yes, depending on your needs, you can use both Newtonsoft.Json and XmlSerializer within the same application.
Post a Comment