The best examples of working with JSON data in C#: practical examples for real projects

If you work in .NET, you can’t escape JSON. APIs, config files, logging, microservices—JSON is everywhere. That’s why developers keep searching for **examples of working with JSON data in C#: practical examples** they can drop straight into real projects instead of wading through dry theory. This guide is exactly that: opinionated, hands-on, and focused on code that actually ships. We’ll walk through a series of real examples that show how to parse JSON, map it to C# classes, handle dynamic data, talk to web APIs, and keep performance in check using modern .NET tools like `System.Text.Json`. Along the way, we’ll touch on trends going into 2024–2025, like source‑generated serializers and why many teams are migrating off older libraries. If you want copy‑paste friendly snippets, real examples from API-style workloads, and clear explanations of what to use and when, you’re in the right place.
Written by
Jamie
Published

Let’s start with concrete code. Here are several examples of working with JSON data in C#: practical examples you’ll actually use:

  • Parsing a simple JSON string into a C# object
  • Serializing a C# object back to JSON
  • Handling nested JSON objects and arrays
  • Working with dynamic or unknown JSON shapes
  • Calling a public web API that returns JSON
  • Customizing property names and date formats
  • Streaming large JSON files without blowing up memory
  • Using source generators for high‑performance JSON in .NET 8/9

We’ll unpack each example of real JSON usage in C#, then layer on more advanced scenarios.


Basic example of parsing JSON into a C# object

Modern .NET apps should start with System.Text.Json from System.Text.Json namespace. It’s fast, built‑in, and actively improved.

using System;
using System.Text.Json;

public class User
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
}

public class Program
{
    public static void Main()
    {
        string json = """
        {
            "id": 1,
            "name": "Ada Lovelace",
            "email": "ada@example.com"
        }
        """;

        var user = JsonSerializer.Deserialize<User>(json);

        Console.WriteLine($"User: {user?.Name} ({user?.Email})");
    }
}

This is the most common example of JSON usage: API returns JSON, your C# app deserializes into a typed model, and you work with that model safely.

Key points:

  • Property names in JSON are case‑insensitive by default in System.Text.Json (configurable).
  • Missing JSON properties map to default values (0, null, empty string if you set it).

Round‑trip examples of working with JSON data in C#: practical examples

You rarely just read JSON; you usually send it back out. Here’s a round‑trip example of turning a C# object into JSON and back.

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class Product
{
    [JsonPropertyName("id")] // customize the JSON field name
    public int ProductId { get; set; }

    [JsonPropertyName("title")]
    public string Name { get; set; } = string.Empty;

    public decimal Price { get; set; }
}

public class Program
{
    public static void Main()
    {
        var product = new Product
        {
            ProductId = 101,
            Name = "Mechanical Keyboard",
            Price = 129.99m
        };

        var options = new JsonSerializerOptions
        {
            WriteIndented = true
        };

        string json = JsonSerializer.Serialize(product, options);
        Console.WriteLine("Serialized JSON:\n" + json);

        var deserialized = JsonSerializer.Deserialize<Product>(json);
        Console.WriteLine(\("Deserialized: {deserialized?.Name} - }\(deserialized?.Price}");
    }
}

This pattern shows up constantly in examples of working with JSON data in C#: practical examples for REST APIs, message queues, and configuration tooling.


Handling nested JSON and arrays: real examples

Most real APIs return nested data. Here’s a realistic order payload with nested objects and arrays.

{
  "orderId": 5001,
  "customer": {
    "id": 42,
    "name": "Grace Hopper"
  },
  "items": [
    { "sku": "BOOK-001", "quantity": 2, "price": 19.99 },
    { "sku": "USB-KEY", "quantity": 1, "price": 9.99 }
  ],
  "createdAt": "2025-01-10T14:32:00Z"
}

C# models:

public class Order
{
    public int OrderId { get; set; }
    public Customer Customer { get; set; } = new();
    public List<OrderItem> Items { get; set; } = new();
    public DateTime CreatedAt { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
}

public class OrderItem
{
    public string Sku { get; set; } = string.Empty;
    public int Quantity { get; set; }
    public decimal Price { get; set; }
}

Deserialization and processing:

using System.Text.Json;

// assume json is the string above
var order = JsonSerializer.Deserialize<Order>(json);

if (order is not null)
{
    decimal total = 0;
    foreach (var item in order.Items)
    {
        total += item.Price * item.Quantity;
    }

    Console.WriteLine($"Order {order.OrderId} for {order.Customer.Name}");
    Console.WriteLine(\("Total: }\(total}");
}

These nested structures are classic examples of working with JSON data in C#: practical examples for e‑commerce, logistics, and analytics pipelines.


Working with dynamic JSON when the shape is unknown

Sometimes you don’t control the JSON schema. Maybe the upstream team keeps changing fields, or you’re building a generic viewer. In those cases, you can use JsonDocument or JsonNode.

using System;
using System.Text.Json;

public static class DynamicJsonDemo
{
    public static void Run()
    {
        string json = """
        {
          "status": "ok",
          "data": {
            "count": 3,
            "values": [1, 2, 3]
          }
        }
        """;

        using JsonDocument doc = JsonDocument.Parse(json);
        JsonElement root = doc.RootElement;

        string status = root.GetProperty("status").GetString() ?? "unknown";
        int count = root.GetProperty("data").GetProperty("count").GetInt32();

        Console.WriteLine($"Status: {status}, Count: {count}");

        foreach (var value in root.GetProperty("data").GetProperty("values").EnumerateArray())
        {
            Console.WriteLine($"Value: {value.GetInt32()}");
        }
    }
}

JsonDocument keeps things efficient and is great for inspectors, gateways, or logging tools that need to work with arbitrary JSON. These are the best examples when you need flexibility more than strict typing.


Real examples of working with JSON data in C#: practical examples for HTTP APIs

Most .NET developers hit JSON through HTTP. Let’s call a real‑world style API using HttpClient and System.Text.Json.

Imagine a weather API returning:

{
  "city": "Seattle",
  "temperatureF": 55.2,
  "conditions": "Cloudy"
}

C# client code:

using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

public class WeatherResponse
{
    public string City { get; set; } = string.Empty;
    public double TemperatureF { get; set; }
    public string Conditions { get; set; } = string.Empty;
}

public class WeatherClient
{
    private readonly HttpClient _httpClient;

    public WeatherClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<WeatherResponse?> GetWeatherAsync(string city)
    {
        string url = $"/api/weather?city={Uri.EscapeDataString(city)}";
        return await _httpClient.GetFromJsonAsync<WeatherResponse>(url);
    }
}

This is one of the best examples of working with JSON data in C#: practical examples that map directly to microservices, third‑party APIs, and even government data sources like the U.S. National Weather Service JSON feeds from weather.gov.


Controlling property names, casing, and null handling

APIs are picky about JSON formats. You often need to:

  • Use camelCase in JSON while keeping PascalCase in C#
  • Ignore null properties
  • Accept unknown fields without throwing
using System.Text.Json;

var options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
    PropertyNameCaseInsensitive = true
};

var user = new
{
    Id = 1,
    FirstName = "Linus",
    LastName = (string?)null
};

string json = JsonSerializer.Serialize(user, options);
Console.WriteLine(json); // {"id":1,"firstName":"Linus"}

These knobs show up constantly in examples of working with JSON data in C#: practical examples when you integrate with front‑end frameworks like React or Angular that expect specific casing rules.


Streaming and large-file examples of working with JSON data in C#: practical examples

With modern analytics and logging, JSON payloads can be huge: gigabyte‑scale log files, telemetry from IoT devices, or large exports from public datasets (for example, health or education data from data.gov). Loading everything into memory is a great way to get a late‑night page from your SRE.

Here’s a streaming example that processes each JSON object from a large array one by one:

using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

public static class JsonStreamingDemo
{
    public static async Task ProcessLargeFileAsync(string path)
    {
        await using FileStream fs = File.OpenRead(path);
        using JsonDocument doc = await JsonDocument.ParseAsync(fs);

        JsonElement root = doc.RootElement;
        if (root.ValueKind != JsonValueKind.Array)
        {
            throw new InvalidOperationException("Expected a JSON array at the root.");
        }

        foreach (var element in root.EnumerateArray())
        {
            // Minimal example: just print an ID field if present
            if (element.TryGetProperty("id", out var idProperty))
            {
                Console.WriteLine($"Record ID: {idProperty.GetInt32()}");
            }
        }
    }
}

For truly massive inputs, you can go even more incremental using Utf8JsonReader to parse tokens as a forward‑only stream. That pattern shows up in data engineering examples of working with JSON data in C#: practical examples where memory usage matters.


Custom converters: real examples for dates and enums

APIs don’t always agree on formats. One API might send dates as ISO 8601 strings, another as Unix timestamps. Here’s an example of a custom converter that reads and writes Unix timestamps.

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class UnixTimestampConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        long seconds = reader.GetInt64();
        return DateTimeOffset.FromUnixTimeSeconds(seconds).UtcDateTime;
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        long seconds = new DateTimeOffset(value).ToUnixTimeSeconds();
        writer.WriteNumberValue(seconds);
    }
}

public class Event
{
    [JsonConverter(typeof(UnixTimestampConverter))]
    public DateTime OccurredAt { get; set; }

    public string Description { get; set; } = string.Empty;
}

This is an example of customization you’ll need when integrating with legacy services or third‑party partners that use older timestamp formats.


High‑performance examples of working with JSON data in C#: practical examples (2024–2025)

In .NET 7–9, System.Text.Json added source‑generated serializers. For hot code paths—like high‑traffic APIs—these can cut allocations and boost throughput.

Generator setup:

using System.Text.Json.Serialization;

[JsonSerializable(typeof(User))]
[JsonSerializable(typeof(Product))]
internal partial class AppJsonContext : JsonSerializerContext
{
}

Usage:

var user = new User { Id = 1, Name = "Ada", Email = "ada@example.com" };

string json = JsonSerializer.Serialize(user, AppJsonContext.Default.User);
var deserialized = JsonSerializer.Deserialize("{""id"":1,""name"":""Ada"",""email"":""ada@example.com""}", AppJsonContext.Default.User);

These patterns are the best examples of working with JSON data in C#: practical examples for teams that care about latency and throughput—think trading systems, telemetry ingestion, or API gateways.

Microsoft’s official docs keep an updated guide on System.Text.Json and source generators here: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-source-generation


Validation and safety: JSON in health, education, and regulated domains

If you’re working with JSON data that touches health or education—say, FHIR JSON from healthcare systems or student records—you care a lot about validation and predictable schemas.

In those cases, you’ll often:

  • Define strong C# models that mirror official JSON schemas
  • Use nullable reference types to avoid unexpected nulls
  • Add validation attributes or custom validators

Example with data annotations:

using System.ComponentModel.DataAnnotations;

public class Patient
{
    [Required]
    public string Id { get; set; } = string.Empty;

    [Required]
    [StringLength(100)]
    public string FullName { get; set; } = string.Empty;

    public DateTime? DateOfBirth { get; set; }
}

You deserialize JSON into this model, then run validation before processing or storing it. That approach aligns well with guidance you’ll see in health‑related data contexts from organizations like the National Institutes of Health or educational research from universities such as Harvard University, where data quality and consistency are non‑negotiable.

These are quieter but important examples of working with JSON data in C#: practical examples when your bug reports involve regulators, not just product managers.


FAQ: common questions and examples of JSON in C

Q: What are the most common examples of working with JSON data in C#?
The most common examples include calling REST APIs with HttpClient and System.Text.Json, reading and writing config files, logging structured events, and moving data between microservices. In all of these, you either deserialize JSON into C# models or work with dynamic JSON using JsonDocument.

Q: Can you give an example of converting JSON to a C# list?
Yes. If your JSON is an array like [{"id":1},{"id":2}], you can do:

var items = JsonSerializer.Deserialize<List<MyType>>(json);

This pattern shows up in many examples of working with JSON data in C#: practical examples, especially when APIs return collections of resources.

Q: Should I still use Newtonsoft.Json in 2024–2025?
Newtonsoft.Json is still widely used, especially for older apps or advanced scenarios like polymorphic serialization that System.Text.Json only recently improved. For new .NET 7+ projects, most teams start with System.Text.Json for performance and first‑party support, then add Newtonsoft.Json only if they hit a feature gap.

Q: How do I handle unknown fields in incoming JSON?
By default, System.Text.Json ignores extra fields. If you need to capture them, you can use [JsonExtensionData] on a Dictionary<string, JsonElement> property to store anything that doesn’t map to a known member.

Q: Are there security concerns when working with JSON in C#?
Yes. You should validate and sanitize input, avoid deserializing into types with dangerous side effects, and keep libraries up to date. For sensitive domains like health data, look at broader security guidance from sources such as HHS.gov alongside your C# JSON practices.


If you keep these examples of working with JSON data in C#: practical examples in your toolkit—typed models, dynamic parsing, HTTP integration, streaming, converters, and validation—you’ll be in good shape for most JSON‑heavy workloads you’ll touch in .NET through 2025 and beyond.

Explore More C++ Code Snippets

Discover more examples and insights in this category.

View All C++ Code Snippets