JSON in C#
C# has built-in JSON support through the System.Text.Json namespace, available since .NET Core 3.0. The older Newtonsoft.Json library (also called Json.NET) remains widely used for its flexibility and extra features. Both libraries handle JSON well, and you choose based on your project's needs.
Two Main Approaches
- System.Text.Json — Built into .NET. Fast, lightweight, no installation needed.
- Newtonsoft.Json — Third-party but very popular. Flexible, feature-rich, works with older .NET versions.
Setting Up System.Text.Json
No installation needed for .NET Core 3.0 and later. Add this using statement at the top of your file:
using System.Text.Json;
Setting Up Newtonsoft.Json
Install via NuGet Package Manager:
Install-Package Newtonsoft.Json
Or using the .NET CLI:
dotnet add package Newtonsoft.Json
Creating a C# Class for JSON Mapping
Before working with JSON in C#, define a class that matches your JSON structure. C# properties map to JSON keys.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public double Salary { get; set; }
public bool IsActive { get; set; }
}
Serialization: C# Object to JSON
Serialization converts a C# object into a JSON string. You do this when sending data to an API or saving it to a file.
Using System.Text.Json
using System.Text.Json;
Employee emp = new Employee
{
Id = 301,
Name = "Meera Nair",
Department = "Engineering",
Salary = 85000.00,
IsActive = true
};
// Serialize to JSON string
string json = JsonSerializer.Serialize(emp);
Console.WriteLine(json);
// With indentation (pretty print)
string prettyJson = JsonSerializer.Serialize(emp, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(prettyJson);
Output
{
"Id": 301,
"Name": "Meera Nair",
"Department": "Engineering",
"Salary": 85000,
"IsActive": true
}
Using Newtonsoft.Json
using Newtonsoft.Json;
Employee emp = new Employee { Id = 301, Name = "Meera Nair", Department = "Engineering", Salary = 85000, IsActive = true };
string json = JsonConvert.SerializeObject(emp, Formatting.Indented);
Console.WriteLine(json);
Deserialization: JSON to C# Object
Deserialization converts a JSON string back into a C# object. You do this when receiving data from an API.
Using System.Text.Json
using System.Text.Json;
string json = "{\"Id\":301,\"Name\":\"Meera Nair\",\"Department\":\"Engineering\",\"Salary\":85000,\"IsActive\":true}";
Employee emp = JsonSerializer.Deserialize<Employee>(json);
Console.WriteLine(emp.Name); // Meera Nair
Console.WriteLine(emp.Department); // Engineering
Console.WriteLine(emp.IsActive); // True
Using Newtonsoft.Json
using Newtonsoft.Json;
string json = "{\"Id\":301,\"Name\":\"Meera Nair\",\"Department\":\"Engineering\",\"Salary\":85000,\"IsActive\":true}";
Employee emp = JsonConvert.DeserializeObject<Employee>(json);
Console.WriteLine(emp.Name);
Diagram: C# and JSON Flow
SERIALIZATION
--------------
C# Object (Employee)
|
v
JsonSerializer.Serialize() OR JsonConvert.SerializeObject()
|
v
JSON String
DESERIALIZATION
----------------
JSON String
|
v
JsonSerializer.Deserialize<Employee>() OR JsonConvert.DeserializeObject<Employee>()
|
v
C# Object (Employee) with all properties set
Working with JSON Arrays in C#
List of Objects to JSON
using System.Collections.Generic;
using System.Text.Json;
List<Employee> employees = new List<Employee>
{
new Employee { Id = 301, Name = "Meera Nair", Department = "Engineering", Salary = 85000, IsActive = true },
new Employee { Id = 302, Name = "Karan Shah", Department = "Marketing", Salary = 65000, IsActive = false }
};
string json = JsonSerializer.Serialize(employees, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);
JSON Array to C# List
using System.Collections.Generic;
using System.Text.Json;
string json = "[{\"Id\":301,\"Name\":\"Meera Nair\",\"Department\":\"Engineering\",\"Salary\":85000,\"IsActive\":true}]";
List<Employee> employees = JsonSerializer.Deserialize<List<Employee>>(json);
foreach (var emp in employees)
{
Console.WriteLine(emp.Name);
}
Reading a JSON File in C#
using System.IO;
using System.Text.Json;
// Read all text from the file
string jsonContent = File.ReadAllText("employees.json");
// Deserialize
List<Employee> employees = JsonSerializer.Deserialize<List<Employee>>(jsonContent);
foreach (var emp in employees)
{
Console.WriteLine($"{emp.Id}: {emp.Name}");
}
Writing a JSON File in C#
using System.IO;
using System.Text.Json;
Employee newEmp = new Employee { Id = 303, Name = "Divya Pillai", Department = "Design", Salary = 72000, IsActive = true };
string json = JsonSerializer.Serialize(newEmp, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("new-employee.json", json);
Console.WriteLine("File saved!");
Handling Nested JSON in C#
public class Address
{
public string City { get; set; }
public string State { get; set; }
public string PinCode { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
string json = @"{
""Id"": 301,
""Name"": ""Meera Nair"",
""Address"": {
""City"": ""Bangalore"",
""State"": ""Karnataka"",
""PinCode"": ""560001""
}
}";
Employee emp = JsonSerializer.Deserialize<Employee>(json);
Console.WriteLine(emp.Address.City); // Bangalore
Console.WriteLine(emp.Address.State); // Karnataka
Customizing JSON Property Names
By default, C# property names in JSON keep their original casing. You can change this behavior with attributes or options.
Using JsonPropertyName Attribute
using System.Text.Json.Serialization;
public class Employee
{
[JsonPropertyName("employee_id")]
public int Id { get; set; }
[JsonPropertyName("full_name")]
public string Name { get; set; }
}
This outputs employee_id and full_name in JSON instead of Id and Name. This is useful when your API expects snake_case keys but your C# code uses PascalCase.
Applying Camel Case Globally
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
string json = JsonSerializer.Serialize(emp, options);
// Output keys: "id", "name", "department" (camelCase)
Handling null Values
public class Product
{
public string Name { get; set; }
public double? DiscountPrice { get; set; } // Nullable double
}
string json = "{\"Name\":\"Laptop Stand\",\"DiscountPrice\":null}";
Product p = JsonSerializer.Deserialize<Product>(json);
if (p.DiscountPrice == null)
{
Console.WriteLine("No discount available");
}
Ignoring Null Values During Serialization
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
string json = JsonSerializer.Serialize(product, options);
// Keys with null values are excluded from output
System.Text.Json vs Newtonsoft.Json
Feature System.Text.Json Newtonsoft.Json
------- ---------------- ---------------
Built into .NET Yes No (NuGet install)
Speed Faster Slightly slower
Flexibility Moderate Very high
Required .NET version .NET Core 3.0+ Any .NET version
JSON Path support No Yes
Dynamic JSON without class Limited Easy (JObject)
Summary
C# handles JSON with System.Text.Json (built-in, fast) or Newtonsoft.Json (flexible, feature-rich). Define C# classes that match your JSON structure, then use Serialize and Deserialize methods to convert between objects and JSON strings. Use nullable types for fields that may be null. Apply property name customization when your API uses a different naming convention than your C# code.
