C# Work with JSON

Learn JSON serialization and deserialization in C#

📦 Working with JSON in C#

JSON (JavaScript Object Notation) is a lightweight data format. C# provides System.Text.Json and Newtonsoft.Json libraries to easily convert objects to JSON strings (serialize) and JSON strings back to objects (deserialize).


// Simple JSON serialization
using System.Text.Json;

var person = new { Name = "John", Age = 30 };
string json = JsonSerializer.Serialize(person);
Console.WriteLine(json);
                                    

Output:

{"Name":"John","Age":30}

Understanding JSON in C#

JSON is essential for modern applications, especially web APIs and data exchange. C# makes JSON handling simple with built-in serialization. You can convert C# objects to JSON format for storage or transmission, and parse JSON data back into strongly-typed objects for easy manipulation in your code.

📤

Serialize

Convert object to JSON

string json = 
  JsonSerializer.Serialize(obj);
📥

Deserialize

Convert JSON to object

var obj = JsonSerializer
  .Deserialize<Person>(json);
📄

Read from File

Load JSON from file

string json = 
  File.ReadAllText("data.json");
var obj = JsonSerializer
  .Deserialize<T>(json);
💾

Write to File

Save JSON to file

string json = 
  JsonSerializer.Serialize(obj);
File.WriteAllText("data.json", json);

🔹 Serialize Object to JSON

Serializing a C# object to JSON converts its data into a lightweight, text-based format for storage or transmission. Use Newtonsoft.Json (Json.NET) or System.Text.Json: call JsonConvert.SerializeObject(yourObject) to produce a JSON string. Customize with attributes like [JsonProperty] for naming. JSON is widely used in APIs and web services due to its readability and compatibility with JavaScript and other languages.

using System;
using System.Text.Json;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

class Program
{
    static void Main()
    {
        // Create object
        Person person = new Person
        {
            Name = "John Doe",
            Age = 30,
            City = "New York"
        };
        
        // Serialize to JSON
        string json = JsonSerializer.Serialize(person);
        
        Console.WriteLine("Serialized JSON:");
        Console.WriteLine(json);
        
        // Pretty print with indentation
        var options = new JsonSerializerOptions { WriteIndented = true };
        string prettyJson = JsonSerializer.Serialize(person, options);
        
        Console.WriteLine("\nPretty JSON:");
        Console.WriteLine(prettyJson);
    }
}

Output:

Serialized JSON:
{"Name":"John Doe","Age":30,"City":"New York"}

Pretty JSON:
{
  "Name": "John Doe",
  "Age": 30,
  "City": "New York"
}

🔹 Deserialize JSON to Object

Deserializing JSON back to a C# object reconstructs the object from a JSON string, enabling data consumption. Utilize JsonConvert.DeserializeObject<YourType>(jsonString) to map JSON properties to object properties. Ensure your C# class structure matches the JSON schema. Handle exceptions for malformed JSON. This process is essential for reading API responses or configuration files.

using System;
using System.Text.Json;

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public bool InStock { get; set; }
}

class Program
{
    static void Main()
    {
        // JSON string
        string json = @"{
            ""Id"": 101,
            ""Name"": ""Laptop"",
            ""Price"": 999.99,
            ""InStock"": true
        }";
        
        try
        {
            // Deserialize JSON to object
            Product product = JsonSerializer.Deserialize(json);
            
            Console.WriteLine("Deserialized Object:");
            Console.WriteLine($"ID: {product.Id}");
            Console.WriteLine($"Name: {product.Name}");
            Console.WriteLine($"Price: ${product.Price}");
            Console.WriteLine($"In Stock: {product.InStock}");
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"JSON Error: {ex.Message}");
        }
    }
}

Output:

Deserialized Object:
ID: 101
Name: Laptop
Price: $999.99
In Stock: True

🔹 Work with JSON Arrays

Handling JSON arrays in C# involves serializing and deserializing collections like lists or arrays. Serialize a List<T> directly to produce a JSON array. Deserialize a JSON array into a typed collection using List<YourType>. Use LINQ to query or transform the data post-deserialization. This is common when dealing with multiple records from an API or storing sets of structured data.

using System;
using System.Collections.Generic;
using System.Text.Json;

class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Grade { get; set; }
}

class Program
{
    static void Main()
    {
        // Create list of students
        List students = new List
        {
            new Student { Id = 1, Name = "Alice", Grade = 95 },
            new Student { Id = 2, Name = "Bob", Grade = 87 },
            new Student { Id = 3, Name = "Charlie", Grade = 92 }
        };
        
        // Serialize list to JSON
        var options = new JsonSerializerOptions { WriteIndented = true };
        string json = JsonSerializer.Serialize(students, options);
        
        Console.WriteLine("JSON Array:");
        Console.WriteLine(json);
        
        // Deserialize back to list
        List deserializedStudents = 
            JsonSerializer.Deserialize>(json);
        
        Console.WriteLine("\nDeserialized Students:");
        foreach (var student in deserializedStudents)
        {
            Console.WriteLine($"{student.Name}: {student.Grade}%");
        }
    }
}

Output:

JSON Array:
[
  {
    "Id": 1,
    "Name": "Alice",
    "Grade": 95
  },
  {
    "Id": 2,
    "Name": "Bob",
    "Grade": 87
  },
  {
    "Id": 3,
    "Name": "Charlie",
    "Grade": 92
  }
]

Deserialized Students:
Alice: 95%
Bob: 87%
Charlie: 92%

🔹 Read JSON from File

Reading JSON data from a file in C# loads and parses the content into usable objects. Employ File.ReadAllText(filePath) to get the JSON string, then deserialize as usual. For large files, consider streaming with System.Text.Json.JsonSerializer.DeserializeAsync. Always validate file existence and handle IO exceptions. This method is ideal for configuration, data caches, or local data stores.

using System;
using System.IO;
using System.Text.Json;

class Config
{
    public string AppName { get; set; }
    public string Version { get; set; }
    public int Port { get; set; }
    public bool DebugMode { get; set; }
}

class Program
{
    static void Main()
    {
        string filePath = "config.json";
        
        try
        {
            // Read JSON from file
            string json = File.ReadAllText(filePath);
            
            Console.WriteLine("JSON from file:");
            Console.WriteLine(json);
            
            // Deserialize to object
            Config config = JsonSerializer.Deserialize(json);
            
            Console.WriteLine("\nConfiguration:");
            Console.WriteLine($"App Name: {config.AppName}");
            Console.WriteLine($"Version: {config.Version}");
            Console.WriteLine($"Port: {config.Port}");
            Console.WriteLine($"Debug Mode: {config.DebugMode}");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Config file not found!");
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"Invalid JSON: {ex.Message}");
        }
    }
}

Output:

JSON from file:
{"AppName":"MyApp","Version":"1.0.0","Port":8080,"DebugMode":true}

Configuration:
App Name: MyApp
Version: 1.0.0
Port: 8080
Debug Mode: True

🔹 Write JSON to File

Writing C# objects to a file as JSON persists data in a structured, portable format. Serialize the object to a JSON string, then use File.WriteAllText(filePath, jsonString) to create or overwrite the file. For appending or handling large objects, use StreamWriter. This is useful for saving application state, generating reports, or exporting data for other systems.

using System;
using System.IO;
using System.Text.Json;
using System.Collections.Generic;

class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

class Program
{
    static void Main()
    {
        // Create employee data
        List employees = new List
        {
            new Employee { Id = 1, Name = "John", Department = "IT", Salary = 75000 },
            new Employee { Id = 2, Name = "Jane", Department = "HR", Salary = 65000 },
            new Employee { Id = 3, Name = "Bob", Department = "Sales", Salary = 70000 }
        };
        
        string filePath = "employees.json";
        
        try
        {
            // Serialize with formatting
            var options = new JsonSerializerOptions 
            { 
                WriteIndented = true 
            };
            string json = JsonSerializer.Serialize(employees, options);
            
            // Write to file
            File.WriteAllText(filePath, json);
            
            Console.WriteLine($"✓ Data saved to {filePath}");
            Console.WriteLine($"Total employees: {employees.Count}");
            Console.WriteLine("\nJSON Content:");
            Console.WriteLine(json);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Output:

✓ Data saved to employees.json
Total employees: 3

JSON Content:
[
  {
    "Id": 1,
    "Name": "John",
    "Department": "IT",
    "Salary": 75000
  },
  {
    "Id": 2,
    "Name": "Jane",
    "Department": "HR",
    "Salary": 65000
  },
  {
    "Id": 3,
    "Name": "Bob",
    "Department": "Sales",
    "Salary": 70000
  }
]

🔹 Nested JSON Objects

Working with nested JSON objects in C# requires classes that mirror the hierarchical structure. Define child classes or complex properties within your main class. Serialization/deserialization will automatically handle nesting. Use attributes for custom mappings if property names differ. This accommodates complex data models like orders with line items or users with addresses.

using System;
using System.Text.Json;
using System.Collections.Generic;

class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
}

class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
    public List Hobbies { get; set; }
}

class Program
{
    static void Main()
    {
        // Create nested object
        User user = new User
        {
            Id = 1,
            Name = "Alice Johnson",
            Address = new Address
            {
                Street = "123 Main St",
                City = "Boston",
                ZipCode = "02101"
            },
            Hobbies = new List { "Reading", "Coding", "Gaming" }
        };
        
        // Serialize
        var options = new JsonSerializerOptions { WriteIndented = true };
        string json = JsonSerializer.Serialize(user, options);
        
        Console.WriteLine("Nested JSON:");
        Console.WriteLine(json);
        
        // Deserialize
        User deserializedUser = JsonSerializer.Deserialize(json);
        
        Console.WriteLine("\nAccessing nested data:");
        Console.WriteLine($"Name: {deserializedUser.Name}");
        Console.WriteLine($"City: {deserializedUser.Address.City}");
        Console.WriteLine($"Hobbies: {string.Join(", ", deserializedUser.Hobbies)}");
    }
}

Output:

Nested JSON:
{
  "Id": 1,
  "Name": "Alice Johnson",
  "Address": {
    "Street": "123 Main St",
    "City": "Boston",
    "ZipCode": "02101"
  },
  "Hobbies": [
    "Reading",
    "Coding",
    "Gaming"
  ]
}

Accessing nested data:
Name: Alice Johnson
City: Boston
Hobbies: Reading, Coding, Gaming

🧠 Test Your Knowledge

Which method converts a C# object to JSON string?