C# Object to JSON: Serialize with System.Text.Json (and More)
Serialize a C# object to JSON with System.Text.Json: pretty-print, camelCase, save to a file, and deserialize. Plus Newtonsoft, CSV to JSON, XML, YAML, TOML.
To convert a C# object to JSON, call JsonSerializer.Serialize from System.Text.Json. It’s built into modern .NET, so there’s nothing to install.
using System.Text.Json;
var friend = new Friend{ Id = 1, Name = "Khalid Abuhakmeh", Met = new DateTime(2026, 11, 25, 9, 30, 0), Debt = 10m};
var json = JsonSerializer.Serialize(friend);Console.WriteLine(json);
public class Friend{ public int Id { get; set; } public string? Name { get; set; } public DateTime Met { get; set; } public decimal Debt { get; set; }}{"Id":1,"Name":"Khalid Abuhakmeh","Met":"2026-11-25T09:30:00","Debt":10}That’s the whole answer for most apps. The rest of this post covers the options you’ll want next (pretty-printing, camelCase, saving to a file, reading JSON back), then how to serialize the same object to XML, YAML, CSV, and TOML. The samples target .NET 10.
How do I serialize an object to JSON in C#?
Use JsonSerializer.Serialize(object) for a string, or JsonSerializer.Serialize<T>(value) when you want the generic overload. It serializes public properties by default, handles nested objects, lists, and dictionaries, and writes DateTime as ISO 8601. System.Text.Json has been in the shared framework since .NET Core 3.0, and ASP.NET Core uses it for request and response bodies.
For older projects or specific needs, Newtonsoft.Json (JSON.NET) does the same job:
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(friend);{"Id":1,"Name":"Khalid Abuhakmeh","Met":"2026-11-25T09:30:00","Debt":10.0}Notice the 10.0. Newtonsoft keeps the decimal point; System.Text.Json writes 10.
How do I pretty-print JSON in C#?
Set WriteIndented on JsonSerializerOptions. Create the options once and reuse them, because each new instance rebuilds the serializer’s metadata cache.
var options = new JsonSerializerOptions { WriteIndented = true };var json = JsonSerializer.Serialize(friend, options);{ "Id": 1, "Name": "Khalid Abuhakmeh", "Met": "2026-11-25T09:30:00", "Debt": 10}With Newtonsoft, pass Formatting.Indented to JsonConvert.SerializeObject.
How do I serialize C# properties as camelCase?
Pass JsonSerializerDefaults.Web to the options constructor. It sets PropertyNamingPolicy to camelCase, makes property matching case-insensitive on read, and allows numbers in strings. It’s the same set of defaults ASP.NET Core uses.
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);var json = JsonSerializer.Serialize(friend, options);{"id":1,"name":"Khalid Abuhakmeh","met":"2026-11-25T09:30:00","debt":10}If you only want camelCase, set PropertyNamingPolicy = JsonNamingPolicy.CamelCase on its own.
How do I ignore null properties when serializing?
Set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull. To ignore one property instead of all of them, put [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] on it.
var options = new JsonSerializerOptions{ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull};
var json = JsonSerializer.Serialize(new Friend { Id = 2 }, options);JsonIgnoreCondition lives in System.Text.Json.Serialization. The result leaves out Name:
{"Id":2,"Met":"0001-01-01T00:00:00","Debt":0}How do I save a C# object to a JSON file?
The shortest route is File.WriteAllText with the serialized string. For larger objects, SerializeAsync writes straight to a FileStream without building the whole string first.
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web) { WriteIndented = true };
// simple: serialize to a string, then write itFile.WriteAllText("friend.json", JsonSerializer.Serialize(friend, options));
// streaming: serialize directly into the fileawait using var stream = File.Create("friend.json");await JsonSerializer.SerializeAsync(stream, friend, options);File.Create truncates an existing file, so you won’t end up with leftover bytes from a longer previous version.
How do I deserialize JSON back to a C# object?
Use JsonSerializer.Deserialize<T> for a string and DeserializeAsync<T> for a stream.
var friend = JsonSerializer.Deserialize<Friend>(json);
await using var stream = File.OpenRead("friend.json");var fromFile = await JsonSerializer.DeserializeAsync<Friend>(stream, options);Pass the same options you used to write the file. If the file is camelCase and you read it with default options, property names won’t match and you’ll get default values. For error messages and mismatches, see solving .NET JSON deserialization issues. For interfaces and base classes, see polymorphic serialization with System.Text.Json.
How do I use source generation for faster, AOT-friendly JSON?
Reflection-based serialization doesn’t work well with trimming and Native AOT. Declare a JsonSerializerContext and let the compiler generate the serialization code at build time.
using System.Text.Json.Serialization;
[JsonSerializable(typeof(Friend))]public partial class FriendContext : JsonSerializerContext;var json = JsonSerializer.Serialize(friend, FriendContext.Default.Friend);It produces the same output as before, with less startup work. For a fuller walkthrough in a web API, read speeding up ASP.NET Core JSON APIs with source generators.
System.Text.Json vs Newtonsoft.Json: which should I use?
| System.Text.Json | Newtonsoft.Json 13.0.4 | |
|---|---|---|
| Ships with .NET | Yes | No, NuGet package |
| Default in ASP.NET Core | Yes | Opt-in |
| Native AOT / trimming | Yes, with source generation | Limited |
| Serialize call | JsonSerializer.Serialize(obj) |
JsonConvert.SerializeObject(obj) |
Decimal 10m default output |
10 |
10.0 |
| Default property matching on read | Case-sensitive | Case-insensitive |
Extras (JObject, JsonPath, many converters) |
Fewer built in (JsonNode covers dynamic JSON) |
Extensive |
Start with System.Text.Json. Add Newtonsoft only when you depend on a feature it has or an existing codebase already uses it.
How do I convert CSV to JSON in C#?
Read the rows into objects with CsvHelper, then serialize the list. Given this friends.csv:
Id,Name,Met,Debt1,Khalid Abuhakmeh,2026-11-25T09:30:00,102,Maria,2026-01-02T00:00:00,5.5using System.Globalization;using System.Text.Json;using CsvHelper;
using var reader = new StreamReader("friends.csv");using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
var friends = csv.GetRecords<Friend>().ToList();
var json = JsonSerializer.Serialize(friends, new JsonSerializerOptions { WriteIndented = true });[ { "Id": 1, "Name": "Khalid Abuhakmeh", "Met": "2026-11-25T09:30:00", "Debt": 10 }, { "Id": 2, "Name": "Maria", "Met": "2026-01-02T00:00:00", "Debt": 5.5 }]GetRecords<T> streams rows lazily, so call ToList() (or serialize with SerializeAsync over an IAsyncEnumerable<T>) before the reader is disposed. Always pass CultureInfo.InvariantCulture for data files, so decimals and dates don’t change with the machine’s locale.
How do I convert a C# object to XML?
Use XmlSerializer from System.Xml.Serialization. It’s built in. Create the serializer once per type and reuse it, because building one is expensive.
using System.Xml.Serialization;
var serializer = new XmlSerializer(typeof(Friend));
using var writer = new StringWriter();serializer.Serialize(writer, friend);var xml = writer.ToString();<?xml version="1.0" encoding="utf-16"?><Friend xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Id>1</Id> <Name>Khalid Abuhakmeh</Name> <Met>2026-11-25T09:30:00</Met> <Debt>10</Debt></Friend>The utf-16 declaration comes from StringWriter. Write to a MemoryStream or FileStream if you need UTF-8. Attributes such as [XmlAttribute] and [XmlElement] control the shape.
How do I convert a C# object to YAML?
Use YamlDotNet (18.1.0). YAML suits configuration files, such as CI pipelines.
using YamlDotNet.Serialization;
var yaml = new SerializerBuilder().Build().Serialize(friend);Id: 1Name: Khalid AbuhakmehMet: 2026-11-25T09:30:00.0000000Debt: 10Add .WithNamingConvention(CamelCaseNamingConvention.Instance) to the builder (from YamlDotNet.Serialization.NamingConventions) if your target expects camelCase keys.
How do I convert a C# object to CSV?
Use CsvHelper (33.1.0 in these samples) again, this time with CsvWriter.
using System.Globalization;using CsvHelper;
using var writer = new StringWriter();using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
csv.WriteRecords(new[] { friend });
var text = writer.ToString();Id,Name,Met,Debt1,Khalid Abuhakmeh,11/25/2026 09:30:00,10The Met column uses the current culture’s date format by default (this output is from InvariantCulture). Set a format with [Format("yyyy-MM-dd")] or a type converter if the consumer expects ISO dates.
CsvHelper 34 is a rewrite with a different API, so the code above targets 33.x. Check the 34 release notes before upgrading.
How do I convert a C# object to TOML?
The Nett library has had no release since 2019. Use Tomlyn (2.11.1) instead.
using Tomlyn;
var toml = TomlSerializer.Serialize(friend);Id = 1Name = "Khalid Abuhakmeh"Met = 2026-11-25T09:30:00Debt = 10.0TOML is a good fit for configuration files you edit by hand. For data exchange, JSON or XML is usually the better choice.
FAQ
What is the best way to convert an object to JSON in C#?
JsonSerializer.Serialize(obj) from System.Text.Json. It’s built into .NET, fast, and the default in ASP.NET Core.
Do I still need Newtonsoft.Json?
Not for new code in most cases. Keep it if you use JObject, JsonPath, or custom converters you already depend on.
Why are my property names PascalCase in the JSON output?
System.Text.Json uses the C# property name unless you set a naming policy. Use JsonSerializerDefaults.Web or PropertyNamingPolicy = JsonNamingPolicy.CamelCase.
Can I serialize to a string or a file?
Both. Serialize returns a string; SerializeAsync writes to any Stream, including a FileStream.
Summary
For JSON, JsonSerializer.Serialize plus a shared JsonSerializerOptions covers most needs. Use the built-in XmlSerializer for XML, YamlDotNet for YAML, CsvHelper for CSV, and Tomlyn for TOML. For CSV to JSON, read with CsvHelper and serialize the list.
Around the web
Comments
Loading comments from GitHub Discussions…