Keywords: C# | JSON Serialization | .NET Development | System.Text.Json | Object Conversion
Abstract: This technical paper provides an in-depth analysis of serializing C# objects to JSON strings in .NET environments. Covering System.Text.Json, Newtonsoft.Json, and JavaScriptSerializer approaches with detailed code examples, performance comparisons, and best practices for different .NET versions and application scenarios.
Fundamentals of Serialization
In modern software development, JSON (JavaScript Object Notation) has become the standard format for data exchange. C#, as a core language of the .NET platform, provides multiple methods for serializing objects into JSON strings. The serialization process converts object states into storable or transmittable formats, while deserialization performs the reverse operation.
Primary Serialization Approaches
The .NET ecosystem offers three main JSON serialization solutions: System.Text.Json, Newtonsoft.Json, and JavaScriptSerializer. Each approach has specific use cases and advantages.
System.Text.Json Approach
As the official solution for .NET Core 3.0 and later versions, System.Text.Json provides high-performance serialization capabilities. Basic usage is as follows:
using System;
using System.Text.Json;
public class MyDate
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Lad
{
public string firstName { get; set; }
public string lastName { get; set; }
public MyDate dateOfBirth { get; set; }
}
class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = JsonSerializer.Serialize(obj);
Console.WriteLine(json);
}
}
Output: {"firstName":"Markoff","lastName":"Chaney","dateOfBirth":{"year":1901,"month":4,"day":30}}
Newtonsoft.Json Approach
Newtonsoft.Json (also known as Json.NET) is a well-established third-party library widely used in .NET 4 and earlier versions:
using Newtonsoft.Json;
// Using the same class definitions
var json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
JavaScriptSerializer Approach
For legacy systems, JavaScriptSerializer remains available, though Microsoft no longer recommends it for new projects:
using System.Web.Script.Serialization;
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(obj);
Console.WriteLine(json);
Serialization Configuration and Optimization
In practical development, fine-grained control over the serialization process is often necessary to meet specific requirements.
Formatted Output
By default, JSON output is minified. Configuration options enable human-readable formatted JSON:
// System.Text.Json
var options = new JsonSerializerOptions
{
WriteIndented = true
};
var formattedJson = JsonSerializer.Serialize(obj, options);
// Newtonsoft.Json
var formattedJson = JsonConvert.SerializeObject(obj, Formatting.Indented);
Property Naming Policies
Convert PascalCase property names to camelCase format:
// System.Text.Json
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
// Newtonsoft.Json
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
};
Ignoring Null Values
Exclude properties with null values to reduce JSON size:
// System.Text.Json
var options = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
// Newtonsoft.Json
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
Advanced Serialization Features
Custom Property Ignoring
Use JsonIgnore attribute to mark properties that should not be serialized:
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
[JsonIgnore]
public decimal FinancialRating { get; set; }
}
DateTime Formatting
Customize serialization format for DateTime objects:
public class CustomDateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-dd"));
}
}
var options = new JsonSerializerOptions();
options.Converters.Add(new CustomDateTimeConverter());
Circular Reference Handling
Manage circular references between objects:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Department Department { get; set; }
}
public class Department
{
public string Name { get; set; }
public List<Employee> Staff { get; set; } = new List<Employee>();
}
// System.Text.Json circular reference handling
var options = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.Preserve
};
Performance Optimization Recommendations
UTF-8 Serialization
Direct serialization to UTF-8 byte arrays can improve performance by 5-10%:
byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes(obj);
Options Instance Reuse
Avoid repeatedly creating JsonSerializerOptions instances:
private static readonly JsonSerializerOptions _options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
// Reuse the same instance
var json1 = JsonSerializer.Serialize(obj1, _options);
var json2 = JsonSerializer.Serialize(obj2, _options);
Version Compatibility Considerations
Choose the appropriate serialization solution based on .NET version:
- .NET 5+: Prefer System.Text.Json for optimal performance
- .NET Framework 4.7.2+: Recommended to use System.Text.Json
- .NET Framework 4.0-4.7.1: Use Newtonsoft.Json
- Legacy Systems: JavaScriptSerializer as alternative option
Best Practices Summary
When selecting serialization approaches in real projects, consider these factors: performance requirements, .NET version, feature needs, and team familiarity. For new projects, strongly prefer System.Text.Json as it offers superior performance and is Microsoft's officially maintained solution. For existing projects already using Newtonsoft.Json stably, continue usage but consider gradual migration to System.Text.Json for new features.